mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 10:03:56 +01:00
Preserve texture set hover in the IOR branch merge
This commit is contained in:
commit
2cbbebfd3f
428 files changed
+24761
-4005
No files matched your search
@@ -0,0 +1,75 @@
|
||||
//! `microAnchor` and `microAmount`: the earlier commands for a generator's micro detail, now its Micro Height read from an anchor point
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{Channel, Generator, LayerId, MicroDetails, Source};
|
||||
|
||||
use crate::commands::bad;
|
||||
use crate::mask_cmds::anchor_source;
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// What `microAnchor` and `microAmount` change on a generator's micro details
|
||||
pub struct AnchoredMicroEdit {
|
||||
/// The anchor point the Micro Height reads (`Some(None)`: `microAnchor: null` empties the slot)
|
||||
anchor: Option<Option<Source>>,
|
||||
/// `microAmount`, 0..1, read as the Height Details Intensity
|
||||
amount: Option<f32>,
|
||||
}
|
||||
|
||||
impl AnchoredMicroEdit {
|
||||
/// The edit `params` ask of a generator on layer `reader` (None when they give neither key)
|
||||
pub fn parse(session: &Session, command: &str, reader: LayerId, params: &Value) -> Result<Option<AnchoredMicroEdit>> {
|
||||
let amount = match params.get("microAmount") {
|
||||
Some(value) => {
|
||||
let amount = value.as_f64().filter(|value| value.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?;
|
||||
Some((amount as f32).clamp(0.0, 1.0))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let anchor = match params.get("microAnchor") {
|
||||
None => None,
|
||||
Some(Value::Null) => Some(None),
|
||||
Some(value) => {
|
||||
let anchor = value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?;
|
||||
|
||||
// The same rule as fills: an anchor below, in the same texture set
|
||||
Some(Some(anchor_source(session, command, reader, LayerId(anchor), Channel::Height)?))
|
||||
}
|
||||
};
|
||||
if anchor.is_none() && amount.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(Some(AnchoredMicroEdit { anchor, amount }))
|
||||
}
|
||||
|
||||
/// The edit made on `generator`: an anchor switches the micro details and their Micro Height on and reads it there; a generator on the earlier model reads it as these keys did before Micro Details
|
||||
pub fn apply(self, command: &str, generator: &mut Generator) -> Result<()> {
|
||||
let kind = generator.kind;
|
||||
let earlier = generator.on_earlier_model();
|
||||
let defaults = MicroDetails::defaults(kind);
|
||||
match (self.anchor, &defaults) {
|
||||
(Some(None), _) => {
|
||||
if let Some(micro) = generator.micro.as_mut() {
|
||||
micro.height_source = None;
|
||||
}
|
||||
}
|
||||
(Some(Some(source)), Some(defaults)) => {
|
||||
let micro = generator.micro.get_or_insert_with(|| Box::new(defaults.clone()));
|
||||
(micro.enabled, micro.height, micro.height_source) = (true, true, Some(source));
|
||||
}
|
||||
(Some(Some(_)), None) => return Err(bad(command, format!("{} has no micro details for `microAnchor`", kind.label()))),
|
||||
(None, _) => {}
|
||||
}
|
||||
|
||||
if let Some(amount) = self.amount {
|
||||
let reads_height = generator.micro.as_mut().filter(|micro| micro.height_source.is_some());
|
||||
let micro = reads_height.ok_or_else(|| bad(command, "give `microAnchor` before `microAmount`: the generator's Micro Height reads nothing"))?;
|
||||
micro.height_intensity = amount * MicroDetails::HEIGHT_INTENSITY_PER_AMOUNT;
|
||||
**micro = micro.as_ref().clone().clamped(kind);
|
||||
}
|
||||
if let Some(micro) = generator.micro.as_mut() {
|
||||
micro.earlier = earlier;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl Session {
|
||||
pub fn bake_name_pairs(&self, texture_set: usize) -> Result<Option<Vec<NamePair>>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let settings = &set.bake.high_poly;
|
||||
let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high);
|
||||
let high = self.doc.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high);
|
||||
|
||||
Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings)))
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ use texturecraft_geom::{BaseColor, Mesh};
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BakeMesh {
|
||||
pub name: String,
|
||||
/// The folder the file was read from, when it was picked from disk this session (projects don't keep it)
|
||||
pub folder: Option<String>,
|
||||
pub bytes: Arc<Vec<u8>>,
|
||||
pub mesh: Arc<Mesh>,
|
||||
pub base_color: Vec<Option<Arc<BaseColor>>>,
|
||||
|
||||
@@ -2,8 +2,7 @@ use super::{BakeMesh, MergedHigh};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
|
||||
/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the
|
||||
/// undo history.
|
||||
/// The high-definition meshes and the cage; undo and redo restore them with the document
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct BakeMeshes {
|
||||
pub(crate) low_base_color: OnceLock<std::result::Result<super::MaterialColors, String>>,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{MergedHigh, StreamedBake, StreamedMap};
|
||||
use crate::{EngineError, Result};
|
||||
use std::sync::Arc;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
|
||||
use texturecraft_compose::BakedMaps;
|
||||
use texturecraft_core::{BakeSettings, BakedMap};
|
||||
use texturecraft_geom::{Bvh, Mesh};
|
||||
@@ -46,13 +46,13 @@ impl BakeTask {
|
||||
let total = maps.len();
|
||||
let mut combined: Option<StreamedBake> = None;
|
||||
|
||||
let mut passes = BakePasses::new(self.request());
|
||||
for (index, map) in maps.iter().copied().enumerate() {
|
||||
let mut settings = self.settings.clone();
|
||||
settings.maps.select([map]);
|
||||
let mut output = self.run_with(&settings, progress)?;
|
||||
let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
let Some(data) = output.maps.remove(&map) else { continue };
|
||||
if combined.is_none() {
|
||||
// Retain unchecked maps once, using the full selection rather than this one-map pass.
|
||||
// Restore unchecked maps once from the full selection
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?;
|
||||
}
|
||||
|
||||
@@ -86,34 +86,34 @@ impl BakeTask {
|
||||
}
|
||||
|
||||
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
|
||||
let mut output = self.run_with(&self.settings, progress)?;
|
||||
let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result<BakeOutput> {
|
||||
fn request(&self) -> BakeRequest<'_> {
|
||||
let high =
|
||||
self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color });
|
||||
let request = BakeRequest {
|
||||
BakeRequest {
|
||||
low_base_color: &self.low_base_color,
|
||||
mesh: &self.mesh,
|
||||
bvh: &self.bvh,
|
||||
material: self.material,
|
||||
settings,
|
||||
settings: &self.settings,
|
||||
high,
|
||||
cage: self.cage.as_deref(),
|
||||
skew: self.skew.as_deref(),
|
||||
cage_paint: self.cage_paint.as_deref(),
|
||||
tiles: self.tiles,
|
||||
};
|
||||
|
||||
let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref())
|
||||
.map_err(|error| EngineError::Other(format!("bake failed: {error}")))?;
|
||||
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bake_error(error: texturecraft_bake::BakeError) -> EngineError {
|
||||
EngineError::Other(format!("bake failed: {error}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -124,6 +124,42 @@ mod tests {
|
||||
const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height];
|
||||
const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height];
|
||||
|
||||
#[test]
|
||||
fn preview_resamples_only_the_displayed_map_for_excluded_tiles() {
|
||||
const PREVIOUS_WIDTH: u32 = 256;
|
||||
const PREVIEW_TILE_PIXELS: u32 = 64;
|
||||
const PREVIOUS_OPACITY: f32 = 0.25;
|
||||
let mut session = Session::new_project("Preview", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
|
||||
let selected = BakedMap::Opacity;
|
||||
session.doc.baked.insert(
|
||||
0,
|
||||
BakedMaps {
|
||||
resolution: PREVIOUS_WIDTH,
|
||||
maps: [selected, BakedMap::WorldNormal, BakedMap::Normal, BakedMap::Height, BakedMap::Position, BakedMap::AmbientOcclusion]
|
||||
.into_iter()
|
||||
.map(|map| (map, Arc::new(vec![PREVIOUS_OPACITY; PREVIOUS_WIDTH as usize * (PREVIOUS_WIDTH as usize / 2) * map.components()])))
|
||||
.collect(),
|
||||
},
|
||||
);
|
||||
|
||||
let mut task = session.bake_map_preview_task(0, selected).unwrap();
|
||||
task.settings.common.resolution = texturecraft_core::BakeResolution::from_pixels(PREVIEW_TILE_PIXELS).unwrap();
|
||||
task.settings.common.dilation = 0;
|
||||
task.tracer = None;
|
||||
super::super::preserve_tiles::take_retained_allocations();
|
||||
let output = task.run(&Progress::new()).unwrap();
|
||||
|
||||
let retained_maps = super::super::preserve_tiles::take_retained_allocations();
|
||||
let other_output_bytes =
|
||||
output.maps.iter().filter(|(map, _)| **map != selected).map(|(_, pixels)| std::mem::size_of_val(pixels.as_slice())).sum::<usize>();
|
||||
eprintln!("atlas={}x{} retained_maps={retained_maps:?} other_output_bytes={other_output_bytes}", output.resolution, output.height);
|
||||
let row = &output.maps[&selected][..output.resolution as usize];
|
||||
assert!(row[..PREVIEW_TILE_PIXELS as usize].iter().any(|&opacity| opacity > PREVIOUS_OPACITY), "the included tile bakes");
|
||||
assert!(row[PREVIEW_TILE_PIXELS as usize..].iter().all(|&opacity| opacity == PREVIOUS_OPACITY), "the excluded tile keeps its previous pixels");
|
||||
assert!(retained_maps.is_empty(), "the preview never allocates buffers for maps it will discard");
|
||||
}
|
||||
|
||||
fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask {
|
||||
let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap();
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_formats::MeshFile;
|
||||
|
||||
use super::mesh_map_command::{ADD_HIGH_POLY_LABEL, parse_mesh, unique_name};
|
||||
use super::{BakeMesh, BakeMeshes, MergedHigh};
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// A high poly file parsed and merged with the meshes it joins, which a worker thread can prepare while the session stays in use
|
||||
pub struct HighPolyLoad {
|
||||
/// The name the file was picked by, before it was made unique in the list
|
||||
file_name: String,
|
||||
added: BakeMesh,
|
||||
/// The list the mesh joined, with it at the end
|
||||
high: Vec<BakeMesh>,
|
||||
/// `high` as bakes see it
|
||||
merged: Option<MergedHigh>,
|
||||
/// Files the mesh refers to that could not be read, as messages for the log
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl HighPolyLoad {
|
||||
/// Parse `file` and merge it with the high polys of `meshes`
|
||||
pub fn prepare(meshes: &BakeMeshes, file: MeshFile) -> Result<Self> {
|
||||
let mut added = parse_mesh(&file.name, file.bytes)?;
|
||||
let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect();
|
||||
added.name = unique_name(&file.name, &taken);
|
||||
|
||||
let mut joined = BakeMeshes { high: meshes.high.clone(), ..Default::default() };
|
||||
joined.high.push(added.clone());
|
||||
joined.rebuild();
|
||||
Ok(Self { file_name: file.name, added, high: joined.high, merged: joined.merged, warnings: file.warnings })
|
||||
}
|
||||
|
||||
/// Read the mesh file at `path`, then [`HighPolyLoad::prepare`] it
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn read(meshes: &BakeMeshes, path: &str) -> Result<Self> {
|
||||
Self::prepare(meshes, crate::file_cmds::read_mesh("bake.highPoly.add", path)?)
|
||||
}
|
||||
|
||||
/// Whether `current` is still the list this mesh was merged into
|
||||
fn joins(&self, current: &[BakeMesh]) -> bool {
|
||||
let joined = &self.high[..self.high.len() - 1];
|
||||
joined.len() == current.len()
|
||||
&& joined.iter().zip(current).all(|(joined, current)| joined.name == current.name && Arc::ptr_eq(&joined.mesh, ¤t.mesh))
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Add a prepared high poly as one undo step; every texture set then bakes from the high polys. Returns its name
|
||||
pub fn apply_high_poly_load(&mut self, load: HighPolyLoad) -> String {
|
||||
let before = self.doc.clone();
|
||||
let meshes = &mut self.doc.bake_meshes;
|
||||
let mut added = load.added.clone();
|
||||
if load.joins(&meshes.high) {
|
||||
meshes.high = load.high;
|
||||
meshes.merged = load.merged;
|
||||
} else {
|
||||
// The list changed while the file loaded, so the mesh joins the list as it is now
|
||||
let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect();
|
||||
added.name = unique_name(&load.file_name, &taken);
|
||||
meshes.high.push(added.clone());
|
||||
meshes.rebuild();
|
||||
}
|
||||
|
||||
let textures = added.base_color.iter().flatten().filter(|color| !color.texels.is_empty()).count();
|
||||
self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", added.name, added.mesh.triangle_count()));
|
||||
self.log.warnings("Baker", load.warnings);
|
||||
for set in &mut self.doc.project.texture_sets {
|
||||
set.bake.high_poly.use_low_as_high = false;
|
||||
}
|
||||
self.push_history(ADD_HIGH_POLY_LABEL, before);
|
||||
added.name
|
||||
}
|
||||
}
|
||||
@@ -9,19 +9,26 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use texturecraft_core::BakePaintTarget;
|
||||
|
||||
use super::{BakeCageInputs, MergedHigh};
|
||||
use super::{BakeCageInputs, HighPolyLoad, MergedHigh};
|
||||
use crate::{BakeMesh, BakeTask, StreamedBake};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_bake::tracing::Tracer;
|
||||
use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress};
|
||||
use texturecraft_core::{
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion,
|
||||
BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings,
|
||||
SelfOcclusion,
|
||||
};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
/// Undo step names of the bake mesh edits
|
||||
pub(super) const ADD_HIGH_POLY_LABEL: &str = "Add high poly mesh";
|
||||
const REMOVE_HIGH_POLY_LABEL: &str = "Remove high poly mesh";
|
||||
const SET_CAGE_LABEL: &str = "Load cage mesh";
|
||||
const REMOVE_CAGE_LABEL: &str = "Remove cage mesh";
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -29,7 +36,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Bake mesh maps",
|
||||
["Mode"],
|
||||
None,
|
||||
"{ts?: index|[indices]|\"all\"|\"selected\", cpu?: true (skip the GPU), ...any bake.settings parameter} → {baked, tracer: [where each set's rays ran]}",
|
||||
"{ts?: index|[indices]|\"all\"|\"selected\", cpu?: true (skip the GPU), ...any bake.settings parameter} → {baked, tracer: [where each set's rays ran]}; settings reach sync partners, only the requested sets bake",
|
||||
always,
|
||||
bake_run
|
||||
),
|
||||
@@ -55,8 +62,11 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))),
|
||||
cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set),
|
||||
cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| {
|
||||
s.bake_meshes.cage = None;
|
||||
s.modified = true;
|
||||
if s.doc.bake_meshes.cage.is_some() {
|
||||
let before = s.doc.clone();
|
||||
s.doc.bake_meshes.cage = None;
|
||||
s.push_history(REMOVE_CAGE_LABEL, before);
|
||||
}
|
||||
Ok(meshes_json(s))
|
||||
}),
|
||||
]
|
||||
@@ -83,39 +93,72 @@ pub fn set_gpu_raytracing(enabled: bool) {
|
||||
|
||||
/// The tracer a bake starting now uses: the installed one while GPU raytracing is on, else none (the CPU)
|
||||
fn chosen_tracer(installed: Option<&Arc<dyn Tracer>>, enabled: bool) -> Option<Arc<dyn Tracer>> {
|
||||
// The coverage build bakes on the CPU, the fallback every GPU failure takes anyway. Its tests run on
|
||||
// a headless runner, and the bake's GPU device is created on a worker thread there: tearing that
|
||||
// GL context down crashes the test process at exit (a wgpu-hal GLES `BadDisplay` panic, or a
|
||||
// SIGSEGV in the driver), which took a different test down on every run. The compute shaders are
|
||||
// never line-covered, so nothing is lost.
|
||||
if cfg!(coverage) {
|
||||
return None;
|
||||
}
|
||||
installed.filter(|_| enabled).cloned()
|
||||
}
|
||||
|
||||
/// A mesh file name made unique among `taken` (and safe as a project file entry).
|
||||
fn unique_name(file_name: &str, taken: &[&str]) -> String {
|
||||
/// A mesh file name made unique among `taken` (and safe as a project file entry)
|
||||
pub(super) fn unique_name(file_name: &str, taken: &[&str]) -> String {
|
||||
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh");
|
||||
let base = texturecraft_formats::sanitize_resource_name(leaf);
|
||||
let mut name = base.clone();
|
||||
let mut n = 2;
|
||||
let mut suffix = 2;
|
||||
while taken.contains(&name.as_str()) {
|
||||
name = format!("{n}_{base}");
|
||||
n += 1;
|
||||
name = format!("{suffix}_{base}");
|
||||
suffix += 1;
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
let h = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let base_color = h.base_color.into_iter().map(|c| c.map(Arc::new)).collect();
|
||||
Ok(BakeMesh { name: file_name.to_string(), bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color })
|
||||
pub(super) fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
|
||||
let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect();
|
||||
let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty());
|
||||
Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color })
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The bake of texture set `texture_set`'s checked maps
|
||||
pub fn bake_task(&self, texture_set: usize) -> Result<BakeTask> {
|
||||
self.bake_task_of(texture_set, None)
|
||||
}
|
||||
|
||||
/// The bake of texture set `texture_set`'s map `map` alone, checked or not
|
||||
pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result<BakeTask> {
|
||||
self.bake_task_of(texture_set, Some(map))
|
||||
}
|
||||
|
||||
/// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles
|
||||
pub fn bake_map_preview_task(&self, texture_set: usize, map: BakedMap) -> Result<BakeTask> {
|
||||
let mut task = self.bake_task_only(texture_set, map)?;
|
||||
task.previous_maps.maps.retain(|&previous_map, _| previous_map == map);
|
||||
Ok(task)
|
||||
}
|
||||
|
||||
fn bake_task_of(&self, texture_set: usize, only: Option<BakedMap>) -> Result<BakeTask> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
if !set.has_enabled_bake_tiles() {
|
||||
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
|
||||
}
|
||||
|
||||
let needs_low_color = set.bake.maps.opacity.is_enabled
|
||||
|| (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
|
||||
let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) {
|
||||
self.bake_meshes
|
||||
let mut settings = set.bake.clone();
|
||||
if let Some(map) = only {
|
||||
settings.maps.select([map]);
|
||||
}
|
||||
|
||||
// Read from the maps that bake, so a map baked alone while unchecked still gets the colours
|
||||
let needs_low_color = settings.maps.opacity.is_enabled
|
||||
|| (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
|
||||
let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) {
|
||||
self.doc
|
||||
.bake_meshes
|
||||
.low_base_color
|
||||
.get_or_init(|| match &self.mesh_source {
|
||||
Some((extension, bytes)) => texturecraft_formats::import_high_poly_bytes(&format!("mesh.{extension}"), bytes)
|
||||
@@ -146,7 +189,7 @@ impl Session {
|
||||
mesh: self.bake_mesh(texture_set)?,
|
||||
bvh: self.bvh.clone(),
|
||||
material: set.material,
|
||||
settings: set.bake.clone(),
|
||||
settings,
|
||||
high,
|
||||
cage,
|
||||
skew,
|
||||
@@ -179,7 +222,7 @@ impl Session {
|
||||
/// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly
|
||||
fn bake_high(&self, texture_set: usize) -> Result<Option<MergedHigh>> {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() })
|
||||
Ok(if set.bake.high_poly.use_low_as_high { None } else { self.doc.bake_meshes.merged.clone() })
|
||||
}
|
||||
|
||||
/// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage
|
||||
@@ -189,7 +232,7 @@ impl Session {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?;
|
||||
let cage = self.doc.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?;
|
||||
Ok(Some(cage.mesh.clone()))
|
||||
}
|
||||
|
||||
@@ -260,74 +303,79 @@ impl Session {
|
||||
Ok(tracer)
|
||||
}
|
||||
|
||||
/// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and
|
||||
/// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name.
|
||||
/// Add a high-definition mesh from file bytes as one undo step; every texture set then bakes from the high polys. Returns its name
|
||||
pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
let mut m = parse_mesh(file_name, bytes)?;
|
||||
let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect();
|
||||
m.name = unique_name(file_name, &taken);
|
||||
let textures = m.base_color.iter().flatten().filter(|c| !c.texels.is_empty()).count();
|
||||
self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", m.name, m.mesh.triangle_count()));
|
||||
let name = m.name.clone();
|
||||
self.bake_meshes.high.push(m);
|
||||
self.bake_meshes.rebuild();
|
||||
for set in &mut self.doc.project.texture_sets {
|
||||
set.bake.high_poly.use_low_as_high = false;
|
||||
}
|
||||
self.modified = true;
|
||||
Ok(name)
|
||||
let file = texturecraft_formats::MeshFile { name: file_name.to_string(), bytes, warnings: Vec::new() };
|
||||
let load = HighPolyLoad::prepare(&self.doc.bake_meshes, file)?;
|
||||
Ok(self.apply_high_poly_load(load))
|
||||
}
|
||||
|
||||
/// Remove high-definition mesh `index`.
|
||||
/// Remove high-definition mesh `index` as one undo step
|
||||
pub fn remove_high_poly(&mut self, index: usize) -> Result<BakeMesh> {
|
||||
if index >= self.bake_meshes.high.len() {
|
||||
if index >= self.doc.bake_meshes.high.len() {
|
||||
return Err(EngineError::Other(format!("no high poly mesh {index}")));
|
||||
}
|
||||
let removed = self.bake_meshes.high.remove(index);
|
||||
self.bake_meshes.rebuild();
|
||||
self.modified = true;
|
||||
|
||||
let before = self.doc.clone();
|
||||
let removed = self.doc.bake_meshes.high.remove(index);
|
||||
self.doc.bake_meshes.rebuild();
|
||||
self.push_history(REMOVE_HIGH_POLY_LABEL, before);
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Use a cage mesh (same triangles as the low poly) from file bytes.
|
||||
/// Use a cage mesh (same triangles as the low poly) from file bytes as one undo step. Returns its name
|
||||
pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
|
||||
let mut m = parse_mesh(file_name, bytes)?;
|
||||
if m.mesh.triangle_count() != self.mesh.triangle_count() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"the cage has {} triangles but the low poly has {}; export the cage from the low poly",
|
||||
m.mesh.triangle_count(),
|
||||
self.mesh.triangle_count()
|
||||
)));
|
||||
}
|
||||
m.name = unique_name(file_name, &[]);
|
||||
m.base_color.clear();
|
||||
let name = m.name.clone();
|
||||
self.bake_meshes.cage = Some(m);
|
||||
self.modified = true;
|
||||
let cage = self.cage_from_bytes(file_name, bytes)?;
|
||||
let name = cage.name.clone();
|
||||
let before = self.doc.clone();
|
||||
self.doc.bake_meshes.cage = Some(cage);
|
||||
self.push_history(SET_CAGE_LABEL, before);
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could
|
||||
/// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`.
|
||||
pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result<Value> {
|
||||
let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? };
|
||||
self.log.warnings("Baker", f.warnings);
|
||||
/// Parse a cage mesh file, refusing one whose triangles are not the low poly's
|
||||
fn cage_from_bytes(&self, file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
|
||||
let mut cage = parse_mesh(file_name, bytes)?;
|
||||
if cage.mesh.triangle_count() != self.mesh.triangle_count() {
|
||||
return Err(EngineError::Other(format!(
|
||||
"the cage has {} triangles but the low poly has {}; export the cage from the low poly",
|
||||
cage.mesh.triangle_count(),
|
||||
self.mesh.triangle_count()
|
||||
)));
|
||||
}
|
||||
|
||||
cage.name = unique_name(file_name, &[]);
|
||||
cage.base_color.clear();
|
||||
Ok(cage)
|
||||
}
|
||||
|
||||
/// Add mesh file `file` as a high poly or the cage, logging what it could not fold in; replies `{name, meshes}` like `bake.highPoly.add` / `bake.cage.set`
|
||||
pub fn add_bake_mesh(&mut self, file: texturecraft_formats::MeshFile, cage: bool) -> Result<Value> {
|
||||
let name = if cage {
|
||||
let name = self.set_cage_bytes(&file.name, file.bytes)?;
|
||||
self.log.warnings("Baker", file.warnings);
|
||||
name
|
||||
} else {
|
||||
let load = HighPolyLoad::prepare(&self.doc.bake_meshes, file)?;
|
||||
self.apply_high_poly_load(load)
|
||||
};
|
||||
Ok(json!({ "name": name, "meshes": meshes_json(self) }))
|
||||
}
|
||||
|
||||
/// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped.
|
||||
/// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped
|
||||
pub(crate) fn load_bake_meshes(&mut self, high: Vec<MeshFile>, cage: Option<MeshFile>) {
|
||||
for (name, bytes) in high {
|
||||
match parse_mesh(&name, bytes) {
|
||||
Ok(m) => self.bake_meshes.high.push(m),
|
||||
Ok(m) => self.doc.bake_meshes.high.push(m),
|
||||
Err(e) => self.log.warn("Baker", format!("skipped high poly mesh: {e}")),
|
||||
}
|
||||
}
|
||||
self.bake_meshes.rebuild();
|
||||
if let Some((name, bytes)) = cage
|
||||
&& let Err(e) = self.set_cage_bytes(&name, bytes)
|
||||
{
|
||||
self.log.warn("Baker", format!("skipped cage mesh: {e}"));
|
||||
self.doc.bake_meshes.rebuild();
|
||||
if let Some((name, bytes)) = cage {
|
||||
match self.cage_from_bytes(&name, bytes) {
|
||||
Ok(cage) => self.doc.bake_meshes.cage = Some(cage),
|
||||
Err(e) => self.log.warn("Baker", format!("skipped cage mesh: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,10 +404,10 @@ impl Session {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The bake meshes for a project file: (high polys, cage).
|
||||
/// The bake meshes for a project file: (high polys, cage)
|
||||
pub(crate) fn saved_bake_meshes(&self) -> (Vec<MeshFile>, Option<MeshFile>) {
|
||||
let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone());
|
||||
(self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry))
|
||||
let entry = |mesh: &BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone());
|
||||
(self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,7 +415,7 @@ impl Session {
|
||||
pub fn meshes_json(s: &Session) -> Value {
|
||||
let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::<Vec<_>>() });
|
||||
let painted = |target| s.doc.bake_paint.get(&(s.ts(), target)).map(|map| json!({ "width": map.width, "height": map.height }));
|
||||
json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::<Vec<_>>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| {
|
||||
json!({ "highPoly": s.doc.bake_meshes.high.iter().map(one).collect::<Vec<_>>(), "cage": s.doc.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| {
|
||||
let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0 };
|
||||
json!({"textureSet": texture_set, "target": target, "width": map.width, "height": map.height, "paintedTexels": map.values.iter().filter(|value| **value != default).count()})
|
||||
}).collect::<Vec<_>>() })
|
||||
@@ -390,14 +438,18 @@ fn high_add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn high_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if boolp(p, "all") == Some(true) {
|
||||
s.bake_meshes.high.clear();
|
||||
s.bake_meshes.rebuild();
|
||||
s.modified = true;
|
||||
if !s.doc.bake_meshes.high.is_empty() {
|
||||
let before = s.doc.clone();
|
||||
s.doc.bake_meshes.high.clear();
|
||||
s.doc.bake_meshes.rebuild();
|
||||
s.push_history(REMOVE_HIGH_POLY_LABEL, before);
|
||||
}
|
||||
return Ok(meshes_json(s));
|
||||
}
|
||||
|
||||
let index = match (u64p(p, "index"), strp(p, "name")) {
|
||||
(Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX),
|
||||
(None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?,
|
||||
(None, Some(n)) => s.doc.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?,
|
||||
(None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")),
|
||||
};
|
||||
s.remove_high_poly(index)?;
|
||||
@@ -408,18 +460,25 @@ fn cage_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true)
|
||||
}
|
||||
|
||||
/// Texture sets named by `ts` (default: the active one).
|
||||
fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result<Vec<usize>> {
|
||||
let n = s.set_count();
|
||||
let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}")));
|
||||
match p.get("ts") {
|
||||
Some(Value::String(a)) if a == "all" => Ok((0..n).collect()),
|
||||
Some(Value::String(a)) if a == "selected" => {
|
||||
Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.common.is_enabled)).collect())
|
||||
/// Texture sets named by `ts` (default: the active one)
|
||||
pub(super) fn sets_param(session: &Session, command: &str, params: &Value) -> Result<Vec<usize>> {
|
||||
let set_count = session.set_count();
|
||||
let parse_index = |value: &Value| {
|
||||
value
|
||||
.as_u64()
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < set_count)
|
||||
.ok_or_else(|| bad(command, format!("invalid texture set {value}")))
|
||||
};
|
||||
|
||||
match params.get("ts") {
|
||||
Some(Value::String(selection)) if selection == "all" => Ok((0..set_count).collect()),
|
||||
Some(Value::String(selection)) if selection == "selected" => {
|
||||
Ok(session.doc.project.texture_sets.iter().enumerate().filter_map(|(index, set)| set.bake.common.is_enabled.then_some(index)).collect())
|
||||
}
|
||||
Some(Value::Array(a)) => a.iter().map(one).collect(),
|
||||
Some(v) => Ok(vec![one(v)?]),
|
||||
None => Ok(vec![s.ts()]),
|
||||
Some(Value::Array(indices)) => indices.iter().map(parse_index).collect(),
|
||||
Some(value) => Ok(vec![parse_index(value)?]),
|
||||
None => Ok(vec![session.ts()]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,14 +524,20 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) ->
|
||||
if let Some(model) = params.get("model") {
|
||||
let replacement: BakeSettings = serde_json::from_value(model.clone()).map_err(|error| bad(command, error.to_string()))?;
|
||||
validate_model_settings(&replacement, command, boolp(params, "preset") == Some(true), None)?;
|
||||
let is_enabled = settings.common.is_enabled;
|
||||
*settings = replacement;
|
||||
let (is_enabled, sync) = (settings.common.is_enabled, std::mem::take(&mut settings.sync));
|
||||
|
||||
// Sync membership is not a setting: only `bake.sync` changes it
|
||||
*settings = BakeSettings { sync, ..replacement };
|
||||
if boolp(params, "preserveEnabled") == Some(true) {
|
||||
settings.common.is_enabled = is_enabled;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(patch) = params.get("patch") {
|
||||
if patch.get("sync").is_some() {
|
||||
return Err(bad(command, "use bake.sync to change sync membership"));
|
||||
}
|
||||
|
||||
let mut model = json!(settings);
|
||||
model_patch::apply_patch(&mut model, patch, command)?;
|
||||
let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?;
|
||||
@@ -708,19 +773,57 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result<
|
||||
}
|
||||
|
||||
fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result<Vec<usize>> {
|
||||
let next = updated_settings(session, params, command)?;
|
||||
let sets = next.iter().map(|(index, _)| *index).collect();
|
||||
if next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)) {
|
||||
session.edit("Bake Settings", |session| {
|
||||
for (index, settings) in next {
|
||||
session.doc.project.texture_set_mut(index)?.bake = settings;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
let targets = updated_settings(session, params, command)?;
|
||||
let sets = targets.iter().map(|(index, _)| *index).collect();
|
||||
let next = with_sync_partners(&session.doc.project, targets, command)?;
|
||||
|
||||
super::sync_command::store(session, "Bake Settings", next)?;
|
||||
Ok(sets)
|
||||
}
|
||||
|
||||
/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's values come out inconsistent
|
||||
fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result<Vec<(usize, BakeSettings)>> {
|
||||
let targets: BTreeMap<usize, BakeSettings> = targets.into_iter().collect();
|
||||
|
||||
// Each explicit target already has its final settings
|
||||
if targets.len() == project.texture_sets.len() {
|
||||
return Ok(targets.into_iter().collect());
|
||||
}
|
||||
|
||||
let mut next: BTreeMap<usize, BakeSettings> = BTreeMap::new();
|
||||
for (target, settings) in &targets {
|
||||
let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue };
|
||||
|
||||
if before == settings {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(changed) = model_patch::changed_fields(&json!(before), &json!(settings)) else { continue };
|
||||
|
||||
let groups = std::iter::once(BakeSyncGroup::Common).chain(BakedMap::ALL.map(BakeSyncGroup::Map));
|
||||
for group in groups {
|
||||
for partner in project.bake_synced_sets(*target, group).into_iter().filter(|partner| !targets.contains_key(partner)) {
|
||||
let Some(set) = project.texture_sets.get(partner) else { continue };
|
||||
|
||||
let entry = next.entry(partner).or_insert_with(|| set.bake.clone());
|
||||
|
||||
let mut model = json!(entry);
|
||||
model_patch::apply_patch(&mut model, &changed, command)?;
|
||||
let patched: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?;
|
||||
entry.copy_group(&patched, group);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A copied value can conflict with a partner's retained settings
|
||||
for settings in next.values() {
|
||||
validate_model_settings(settings, command, false, Some(settings))?;
|
||||
}
|
||||
|
||||
next.extend(targets);
|
||||
Ok(next.into_iter().collect())
|
||||
}
|
||||
|
||||
fn settings(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let sets = set_settings(session, params, "bake.settings")?;
|
||||
let result: Vec<Value> = sets
|
||||
@@ -748,11 +851,15 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
return Ok(json!({"baked": [], "tracer": []}));
|
||||
}
|
||||
|
||||
let next = with_sync_partners(&session.doc.project, next, "bake.run")?;
|
||||
let cpu = boolp(params, "cpu") == Some(true);
|
||||
let tracers = session.edit("Bake mesh maps", |session| {
|
||||
let mut tracers = Vec::with_capacity(next.len());
|
||||
for (index, settings) in next {
|
||||
session.doc.project.texture_set_mut(index)?.bake = settings;
|
||||
}
|
||||
|
||||
let mut tracers = Vec::with_capacity(sets.len());
|
||||
for &index in &sets {
|
||||
let mut task = session.bake_task(index)?;
|
||||
if cpu {
|
||||
task.tracer = None;
|
||||
@@ -818,8 +925,33 @@ mod gpu_raytracing_tests {
|
||||
fn bakes_use_the_installed_gpu_tracer_only_while_gpu_raytracing_is_on() {
|
||||
let installed: Arc<dyn Tracer> = Arc::new(NamedTracer);
|
||||
|
||||
assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), Some("gpu".to_string()));
|
||||
// A coverage build keeps every bake on the CPU: its headless runner has no GPU to bake on
|
||||
let gpu = (!cfg!(coverage)).then(|| "gpu".to_string());
|
||||
assert_eq!(chosen_tracer(Some(&installed), true).map(|tracer| tracer.name()), gpu, "on casts the rays on the GPU");
|
||||
assert!(chosen_tracer(Some(&installed), false).is_none(), "off keeps the rays on the CPU");
|
||||
assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bake_task_tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
#[test]
|
||||
fn a_map_baked_alone_while_unchecked_still_reads_the_low_polys_colours() {
|
||||
let mut session = crate::sample_session(128, 64).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]);
|
||||
let colours = Arc::new(vec![None]);
|
||||
|
||||
// The sample bakes when made, which already read the colours
|
||||
session.doc.bake_meshes.low_base_color = Default::default();
|
||||
assert!(session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())).is_ok());
|
||||
|
||||
assert!(session.bake_task(0).unwrap().low_base_color.is_empty(), "the checked maps need no colours");
|
||||
let task = session.bake_task_only(0, BakedMap::Opacity).unwrap();
|
||||
assert!(Arc::ptr_eq(&task.low_base_color, &colours), "Opacity reads them");
|
||||
assert!(task.settings.maps.opacity.is_enabled);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ mod bake_checks;
|
||||
mod bake_mesh;
|
||||
mod bake_meshes;
|
||||
mod bake_task;
|
||||
mod high_poly_load;
|
||||
mod high_poly_missed;
|
||||
mod layout;
|
||||
mod merged_high;
|
||||
@@ -14,12 +15,14 @@ mod paint_command;
|
||||
mod preserve_tiles;
|
||||
mod streamed_bake;
|
||||
mod streamed_map;
|
||||
mod sync_command;
|
||||
mod tile_command;
|
||||
|
||||
pub use bake_cage_inputs::BakeCageInputs;
|
||||
pub use bake_mesh::BakeMesh;
|
||||
pub use bake_meshes::BakeMeshes;
|
||||
pub use bake_task::BakeTask;
|
||||
pub use high_poly_load::HighPolyLoad;
|
||||
pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed};
|
||||
pub use merged_high::MergedHigh;
|
||||
pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params};
|
||||
@@ -36,5 +39,6 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
let mut commands = mesh_map_command::specs();
|
||||
commands.extend(paint_command::specs());
|
||||
commands.extend(tile_command::specs());
|
||||
commands.extend(sync_command::specs());
|
||||
commands
|
||||
}
|
||||
@@ -9,7 +9,8 @@ pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value {
|
||||
changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({}))
|
||||
}
|
||||
|
||||
fn changed_fields(before: &Value, after: &Value) -> Option<Value> {
|
||||
/// The fields of `after` that differ from `before`, nested as a `bake.settings` patch; `None` when nothing changed
|
||||
pub(super) fn changed_fields(before: &Value, after: &Value) -> Option<Value> {
|
||||
if before == after {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
//! Sharing bake settings between texture sets: live sync groups, and one-off copies from the bake menus
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{BakeSettings, BakeSyncGroup, BakedMap};
|
||||
|
||||
use super::mesh_map_command::sets_param;
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"bake.sync",
|
||||
"Sync bake settings",
|
||||
[],
|
||||
None,
|
||||
"{group: \"common\"|map id, ts: index|[indices]|\"all\"} → {group, ts}; exactly these texture sets share the group's settings from now on, and the ones added take the settings the group shares",
|
||||
always,
|
||||
sync
|
||||
),
|
||||
cmd!(
|
||||
"bake.copy",
|
||||
"Copy bake settings",
|
||||
[],
|
||||
None,
|
||||
"{what: \"settings\"|\"checked\"|\"check\", map?: id, from?: index (default: the active set), ts: index|[indices]|\"all\"} → {ts}; settings: every setting and which maps are checked, or with map that map's settings; checked: which maps are checked; check: check map. Settings also reach the sets sharing a group with a target, whose checkboxes stay their own",
|
||||
always,
|
||||
copy
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn group_param(params: &Value, command: &str) -> Result<BakeSyncGroup> {
|
||||
match strp(params, "group") {
|
||||
Some("common") => Ok(BakeSyncGroup::Common),
|
||||
Some(id) => BakedMap::parse(id).map(BakeSyncGroup::Map).ok_or_else(|| bad(command, format!("unknown group {id}"))),
|
||||
None => Err(bad(command, "`group` must be \"common\" or a mesh map id")),
|
||||
}
|
||||
}
|
||||
|
||||
fn group_id(group: BakeSyncGroup) -> &'static str {
|
||||
match group {
|
||||
BakeSyncGroup::Common => "common",
|
||||
BakeSyncGroup::Map(map) => map.id(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sync(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "bake.sync";
|
||||
let group = group_param(params, COMMAND)?;
|
||||
let members = sets_param(session, COMMAND, params)?;
|
||||
let sets = &session.doc.project.texture_sets;
|
||||
|
||||
let source = session.doc.project.bake_sync_source(group, &members, session.ts());
|
||||
let source = source.and_then(|index| sets.get(index)).map(|set| set.bake.clone());
|
||||
|
||||
let next: Vec<(usize, BakeSettings)> = sets
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, set)| {
|
||||
let mut settings = set.bake.clone();
|
||||
let joins = members.contains(&index);
|
||||
if let Some(source) = source.as_ref().filter(|_| joins && !settings.sync.shares(group)) {
|
||||
settings.copy_group(source, group);
|
||||
}
|
||||
settings.sync.set_shares(group, joins);
|
||||
(index, settings)
|
||||
})
|
||||
.collect();
|
||||
store(session, "Sync bake settings", next)?;
|
||||
Ok(json!({ "group": group_id(group), "ts": members }))
|
||||
}
|
||||
|
||||
fn copy(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const COMMAND: &str = "bake.copy";
|
||||
|
||||
let map = match params.get("map") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => Some(value.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, format!("invalid mesh map {value}")))?),
|
||||
};
|
||||
let from = match params.get("from") {
|
||||
None | Some(Value::Null) => session.ts(),
|
||||
Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad(COMMAND, "`from` must be a texture set index"))?,
|
||||
};
|
||||
let source = session.doc.project.texture_set(from)?.bake.clone();
|
||||
let targets = sets_param(session, COMMAND, params)?;
|
||||
let maps: Vec<BakedMap> = map.map_or_else(|| BakedMap::ALL.to_vec(), |map| vec![map]);
|
||||
|
||||
let mut next: Vec<BakeSettings> = session.doc.project.texture_sets.iter().map(|set| set.bake.clone()).collect();
|
||||
let mut explicit = vec![false; next.len()];
|
||||
for &index in &targets {
|
||||
explicit[index] = true;
|
||||
}
|
||||
|
||||
match strp(params, "what") {
|
||||
Some("settings") => {
|
||||
let groups = map.map_or_else(
|
||||
|| std::iter::once(BakeSyncGroup::Common).chain(maps.iter().map(|map| BakeSyncGroup::Map(*map))).collect(),
|
||||
|map| vec![BakeSyncGroup::Map(map)],
|
||||
);
|
||||
for group in groups {
|
||||
let shared = targets.iter().any(|&index| next[index].sync.shares(group));
|
||||
for (index, settings) in next.iter_mut().enumerate() {
|
||||
if explicit[index] || (shared && settings.sync.shares(group)) {
|
||||
settings.copy_group(&source, group);
|
||||
}
|
||||
}
|
||||
}
|
||||
if map.is_none() {
|
||||
for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| explicit[*index]) {
|
||||
for map in BakedMap::ALL {
|
||||
settings.maps.set_enabled(map, source.maps.is_enabled(map));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(what @ ("checked" | "check")) => {
|
||||
if what == "check" && map.is_none() {
|
||||
return Err(bad(COMMAND, "`check` needs a `map`"));
|
||||
}
|
||||
|
||||
for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| explicit[*index]) {
|
||||
for map in &maps {
|
||||
settings.maps.set_enabled(*map, what == "check" || source.maps.is_enabled(*map));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => return Err(bad(COMMAND, "`what` must be settings, checked or check")),
|
||||
}
|
||||
|
||||
store(session, "Copy bake settings", next.into_iter().enumerate().collect())?;
|
||||
Ok(json!({ "ts": targets }))
|
||||
}
|
||||
|
||||
/// Write each set's `next` bake settings as one undo step labelled `label`; nothing when none changed
|
||||
pub(super) fn store(session: &mut Session, label: &str, next: Vec<(usize, BakeSettings)>) -> Result<()> {
|
||||
let changed =
|
||||
|session: &Session| next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings));
|
||||
if !changed(session) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
session.edit(label, |session| {
|
||||
for (index, settings) in next {
|
||||
session.doc.project.texture_set_mut(index)?.bake = settings;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{execute, sample_session};
|
||||
use texturecraft_core::BakeSettings;
|
||||
|
||||
/// A dilation only presets may hold, above what an edit may set
|
||||
const LEGACY_DILATION: u32 = 200;
|
||||
|
||||
fn session() -> Session {
|
||||
let session = sample_session(128, 32).unwrap();
|
||||
assert_eq!(session.set_count(), 2);
|
||||
session
|
||||
}
|
||||
|
||||
fn bake(session: &Session, index: usize) -> &BakeSettings {
|
||||
&session.doc.project.texture_sets[index].bake
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_saved_before_sync_share_everything() {
|
||||
let settings: BakeSettings = serde_json::from_value(json!({ "common": { "dilation": 4 } })).unwrap();
|
||||
assert!(settings.sync.common);
|
||||
assert!(BakedMap::ALL.iter().all(|map| settings.sync.shares(BakeSyncGroup::Map(*map))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_left_out_of_common_sync_keeps_its_own_common_settings() {
|
||||
let mut session = session();
|
||||
assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0, 1]);
|
||||
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap();
|
||||
|
||||
assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0]);
|
||||
assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Common), [1]);
|
||||
assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync is separate");
|
||||
|
||||
let reached = session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common);
|
||||
execute(&mut session, "bake.settings", &json!({ "ts": reached, "patch": { "common": { "dilation": 7 } } })).unwrap();
|
||||
|
||||
assert_eq!((bake(&session, 0).common.dilation, bake(&session, 1).common.dilation), (7, 32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_joining_a_group_takes_its_settings_and_keeps_its_own_inclusion() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0] })).unwrap();
|
||||
session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 3;
|
||||
session.doc.project.texture_sets[1].bake.common.is_enabled = false;
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap();
|
||||
session.doc.project.texture_sets[1].bake.common.dilation = 5;
|
||||
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": "all" })).unwrap();
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": "all" })).unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 1).maps.ao.parameters, bake(&session, 0).maps.ao.parameters);
|
||||
assert_eq!(bake(&session, 1).common.dilation, bake(&session, 0).common.dilation);
|
||||
assert!(!bake(&session, 1).common.is_enabled, "whether the set bakes is its own");
|
||||
|
||||
session.undo().unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 1).common.dilation, 5, "one undo per sync");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_check_maps_and_carry_settings_without_linking() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "height", "ts": [0] })).unwrap();
|
||||
session.doc.project.texture_sets[0].bake.maps.height.parameters.scaling_divisor = 9.0;
|
||||
|
||||
execute(&mut session, "bake.copy", &json!({ "what": "check", "map": "height", "ts": "all" })).unwrap();
|
||||
|
||||
assert!(bake(&session, 0).maps.height.is_enabled && bake(&session, 1).maps.height.is_enabled);
|
||||
|
||||
execute(&mut session, "bake.copy", &json!({ "what": "settings", "map": "height", "from": 0, "ts": [1] })).unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 1).maps.height.parameters.scaling_divisor, 9.0);
|
||||
assert!(!bake(&session, 1).sync.shares(BakeSyncGroup::Map(BakedMap::Height)), "a copy does not link");
|
||||
|
||||
session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]);
|
||||
execute(&mut session, "bake.copy", &json!({ "what": "checked", "from": 0, "ts": [1] })).unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 1).maps.enabled().collect::<Vec<_>>(), [BakedMap::Normal]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_reaches_the_sets_sharing_the_group_with_its_target() {
|
||||
let mut session = session();
|
||||
let third = session.doc.project.texture_sets[1].clone();
|
||||
session.doc.project.texture_sets.push(third);
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0, 1] })).unwrap();
|
||||
session.doc.project.texture_sets[2].bake.maps.ao.parameters.rays.rays = 3;
|
||||
let height_checked = !bake(&session, 0).maps.is_enabled(BakedMap::Height);
|
||||
session.doc.project.texture_sets[2].bake.maps.set_enabled(BakedMap::Height, height_checked);
|
||||
|
||||
execute(&mut session, "bake.copy", &json!({ "what": "settings", "from": 2, "ts": [0] })).unwrap();
|
||||
|
||||
assert_eq!((bake(&session, 0).maps.ao.parameters.rays.rays, bake(&session, 1).maps.ao.parameters.rays.rays), (3, 3), "set 1 shares AO with set 0");
|
||||
assert!(!bake(&session, 2).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion)));
|
||||
assert_eq!(bake(&session, 0).maps.is_enabled(BakedMap::Height), height_checked, "every setting includes which maps are checked");
|
||||
assert_ne!(bake(&session, 1).maps.is_enabled(BakedMap::Height), height_checked, "the set sharing a group keeps its own checkboxes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_a_preset_on_one_set_keeps_its_sync_groups_and_reaches_the_sets_sharing_them() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [1] })).unwrap();
|
||||
let mut preset = bake(&session, 0).clone();
|
||||
preset.common.dilation = 9;
|
||||
preset.maps.ao.parameters.rays.rays = 5;
|
||||
preset.sync = Default::default();
|
||||
|
||||
let params = json!({ "ts": 0, "model": preset, "preserveEnabled": true, "preset": true });
|
||||
execute(&mut session, "bake.settings", ¶ms).unwrap();
|
||||
|
||||
assert!(!bake(&session, 0).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion)), "a preset is settings, not membership");
|
||||
assert_eq!(bake(&session, 1).common.dilation, 9, "set 1 shares Common Settings with set 0");
|
||||
assert_ne!(bake(&session, 1).maps.ao.parameters.rays.rays, 5, "set 1 no longer shares AO with set 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_to_one_group_leaves_the_other_groups_of_the_sets_sharing_it_alone() {
|
||||
let mut session = session();
|
||||
session.doc.project.texture_sets[1].bake.common.dilation = 3;
|
||||
|
||||
execute(&mut session, "bake.settings", &json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 6 } } } } } })).unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 1).maps.ao.parameters.rays.rays, 6);
|
||||
assert_eq!(bake(&session, 1).common.dilation, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_that_would_leave_a_synced_set_with_an_invalid_interval_changes_no_set() {
|
||||
let mut session = session();
|
||||
session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.max_distance = 0.5;
|
||||
session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.max_distance = 0.05;
|
||||
let before = session.doc.project.texture_sets.clone();
|
||||
|
||||
let patch = json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "min_distance": 0.1 } } } } } });
|
||||
assert!(execute(&mut session, "bake.settings", &patch).is_err(), "set 1 would get a minimum above its maximum");
|
||||
assert_eq!(session.doc.project.texture_sets, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_preset_with_a_legacy_value_loads_on_a_set_sharing_it() {
|
||||
let mut session = session();
|
||||
let mut preset = bake(&session, 0).clone();
|
||||
preset.common.dilation = LEGACY_DILATION;
|
||||
|
||||
execute(&mut session, "bake.settings", &json!({ "ts": 0, "model": preset, "preset": true })).unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 1).common.dilation, LEGACY_DILATION, "set 1 shares Common Settings with set 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_settings_patch_cannot_change_sync_membership() {
|
||||
let mut session = session();
|
||||
let original_sync = bake(&session, 0).sync.clone();
|
||||
|
||||
let result = execute(&mut session, "bake.settings", &json!({ "ts": 0, "patch": { "sync": { "common": false }, "common": { "dilation": 7 } } }));
|
||||
|
||||
assert!(result.is_err(), "membership changes must go through bake.sync");
|
||||
assert_eq!(bake(&session, 0).sync, original_sync);
|
||||
assert_eq!(bake(&session, 0).common.dilation, bake(&session, 1).common.dilation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_copy_selectors_do_not_overwrite_other_settings() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap();
|
||||
execute(&mut session, "bake.settings", &json!({ "ts": 1, "dilation": 7 })).unwrap();
|
||||
let before = session.doc.project.texture_sets.clone();
|
||||
|
||||
for params in [json!({ "what": "settings", "ts": 1, "from": "invalid" }), json!({ "what": "settings", "ts": 1, "map": false })] {
|
||||
let result = execute(&mut session, "bake.copy", ¶ms);
|
||||
|
||||
assert!(result.is_err(), "invalid selector in {params}");
|
||||
assert_eq!(session.doc.project.texture_sets, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_a_bake_shares_settings_without_baking_or_checking_maps_on_partners() {
|
||||
let mut session = session();
|
||||
let previous_resolution = bake(&session, 0).common.resolution;
|
||||
let partner_maps = bake(&session, 1).maps.clone();
|
||||
session.doc.baked.clear();
|
||||
|
||||
let result = execute(&mut session, "bake.run", &json!({ "ts": 0, "resolution": 64, "maps": ["opacity"], "cpu": true })).unwrap();
|
||||
|
||||
assert_eq!(result["baked"], json!([0]));
|
||||
assert_ne!(bake(&session, 0).common.resolution, previous_resolution);
|
||||
assert_eq!(bake(&session, 1).common.resolution, bake(&session, 0).common.resolution);
|
||||
assert_eq!(bake(&session, 1).maps, partner_maps);
|
||||
assert!(!session.doc.baked.contains_key(&1));
|
||||
|
||||
session.undo().unwrap();
|
||||
|
||||
assert_eq!(bake(&session, 0).common.resolution, previous_resolution);
|
||||
assert_eq!(bake(&session, 1).common.resolution, previous_resolution);
|
||||
assert!(session.doc.baked.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Bake preview",
|
||||
[],
|
||||
None,
|
||||
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)",
|
||||
"{show?: \"follow\" (the newest finished map) | \"material\" | \"map:<id>\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. In Bake mode the app's map preview also shows here while Mesh Map Settings is in front. With neither {active: false} (setting `show` is then an error)",
|
||||
always,
|
||||
preview
|
||||
)]
|
||||
@@ -82,18 +82,25 @@ impl Session {
|
||||
/// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before
|
||||
/// changing the preview or view mode. This reads settings without preparing bake geometry.
|
||||
pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> {
|
||||
let orders = sets
|
||||
.iter()
|
||||
.map(|&texture_set| {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
Ok((texture_set, set.bake.maps.enabled().collect()))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
|
||||
let orders = self.bake_preview_orders(sets, None)?;
|
||||
self.bake_preview_begin(orders);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate the entire selection before a bake takes the view or starts its first worker.
|
||||
pub fn bake_preview_orders(&self, sets: &[usize], only: Option<BakedMap>) -> Result<Vec<(usize, Vec<BakedMap>)>> {
|
||||
sets.iter()
|
||||
.map(|&texture_set| {
|
||||
let set = self.doc.project.texture_set(texture_set)?;
|
||||
let maps = match only {
|
||||
Some(map) => vec![map],
|
||||
None => set.bake.maps.enabled().collect(),
|
||||
};
|
||||
Ok((texture_set, maps))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view
|
||||
/// follows the newest map and every set shows neutral values until its maps arrive. The
|
||||
/// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Select camera",
|
||||
[],
|
||||
None,
|
||||
"{index? | name?} (neither, or name \"Default camera\": the default camera framing the mesh)",
|
||||
"{index? | name?} (an omitted or null index and an omitted, null, or \"Default camera\" name frame the mesh)",
|
||||
always,
|
||||
select
|
||||
),
|
||||
@@ -226,24 +226,29 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if u64p(p, "index").is_none() && strp(p, "name").is_none_or(|n| n == DEFAULT_CAMERA) {
|
||||
// The default camera: fov and projection from the display settings, framing the mesh
|
||||
s.selected_camera_name = None;
|
||||
s.camera.fov = s.doc.project.display.fov;
|
||||
s.camera.ortho = false;
|
||||
return crate::execute(s, "viewport.frame", &Value::Null);
|
||||
fn select(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if !params.is_object() && !params.is_null() {
|
||||
return Err(bad("camera.select", "expected a parameter object or null"));
|
||||
}
|
||||
|
||||
let i = which(s, "camera.select", p)?;
|
||||
if let Some(camera) = s.doc.project.cameras.get(i) {
|
||||
// A saved view is clamped against the whole mesh, not against a part framed with F
|
||||
s.camera.scene_radius = s.mesh.radius();
|
||||
apply(&mut s.camera, camera);
|
||||
s.selected_camera_name = Some(camera.name.clone());
|
||||
let default_name = params.get("name").is_none_or(|name| name.is_null() || name.as_str() == Some(DEFAULT_CAMERA));
|
||||
if params.get("index").is_none_or(Value::is_null) && default_name {
|
||||
session.selected_camera_name = None;
|
||||
session.camera.fov = session.doc.project.display.fov;
|
||||
session.camera.ortho = false;
|
||||
return crate::execute(session, "viewport.frame", &Value::Null);
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(crate::view_cmds::camera_json(s))
|
||||
|
||||
let camera_index = which(session, "camera.select", params)?;
|
||||
if let Some(camera) = session.doc.project.cameras.get(camera_index) {
|
||||
// Use the whole mesh radius even after framing a texture set
|
||||
session.camera.scene_radius = session.mesh.radius();
|
||||
apply(&mut session.camera, camera);
|
||||
session.selected_camera_name = Some(camera.name.clone());
|
||||
}
|
||||
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(crate::view_cmds::camera_json(session))
|
||||
}
|
||||
|
||||
/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90
|
||||
@@ -453,6 +458,49 @@ mod tests {
|
||||
assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_camera_selectors_leave_the_current_view_intact() {
|
||||
let mut session = session();
|
||||
execute(&mut session, "camera.set", &json!({"yaw": 30, "target": [1, 2, 3], "fov": 25, "ortho": true})).unwrap();
|
||||
let saved_view = session.camera;
|
||||
execute(&mut session, "camera.add", &json!({"name": "Side"})).unwrap();
|
||||
execute(&mut session, "camera.orbit", &json!({"dx": 15})).unwrap();
|
||||
|
||||
execute(&mut session, "camera.select", &json!({"index": 0, "name": DEFAULT_CAMERA})).unwrap();
|
||||
|
||||
assert_eq!(session.camera, saved_view);
|
||||
assert_eq!(session.selected_camera_name.as_deref(), Some("Side"));
|
||||
|
||||
let revision = session.revision;
|
||||
for params in [
|
||||
json!({"index": -1}),
|
||||
json!({"index": -0.5}),
|
||||
json!({"index": "0"}),
|
||||
json!({"name": false}),
|
||||
json!({"index": -1, "name": DEFAULT_CAMERA}),
|
||||
json!([{"index": 0}]),
|
||||
json!("Side"),
|
||||
] {
|
||||
let result = execute(&mut session, "camera.select", ¶ms);
|
||||
|
||||
assert!(matches!(result, Err(crate::EngineError::BadParams { .. })), "{params}: {result:?}");
|
||||
assert_eq!(session.camera, saved_view);
|
||||
assert_eq!(session.selected_camera_name.as_deref(), Some("Side"));
|
||||
assert_eq!(session.revision, revision);
|
||||
}
|
||||
|
||||
for params in [Value::Null, json!({"index": null, "name": null}), json!({"name": DEFAULT_CAMERA})] {
|
||||
execute(&mut session, "camera.select", &json!({"index": null, "name": "Side"})).unwrap();
|
||||
assert_eq!(session.camera, saved_view);
|
||||
|
||||
execute(&mut session, "camera.select", ¶ms).unwrap();
|
||||
|
||||
assert_eq!(session.selected_camera_name, None);
|
||||
assert!(!session.camera.ortho);
|
||||
assert_eq!(session.camera.fov, session.doc.project.display.fov);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn number_shortcuts_go_to_the_first_nine_cameras() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -117,6 +117,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::layer_ops::specs());
|
||||
v.extend(crate::instance_cmds::specs());
|
||||
v.extend(crate::mask_cmds::specs());
|
||||
v.extend(crate::generator_pick::specs());
|
||||
v.extend(crate::mask_export::specs());
|
||||
v.extend(crate::add_mask_cmds::specs());
|
||||
v.extend(crate::color_selection_cmds::specs());
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
//! The controls of the kinds with only the reference's own controls (3D Distance, 3D Linear Gradient, UV Border Distance, Grayscale Conversion) that `effect.add.generator` and `effect.set` take
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{DrippingRustParameters, Generator, GeneratorGrayscale, GeneratorKind, KindControls, UvCheckerParameters, UvRandomColorParameters};
|
||||
|
||||
use crate::Result;
|
||||
use crate::commands::{bad, boolp, color_of, color_param, f32p, u64p};
|
||||
|
||||
/// The 3D Distance controls: the point's X, Y and Z across the mesh's bounds, then the radius, offset and contrast
|
||||
pub const DISTANCE_KEYS: [&str; 6] = ["distanceX", "distanceY", "distanceZ", "distanceRadius", "distanceOffset", "distanceContrast"];
|
||||
|
||||
/// The 3D Linear Gradient controls: its start and end points ([x, y, z] across the mesh's bounds), balance and contrast
|
||||
pub const LINEAR_GRADIENT_KEYS: [&str; 4] = ["gradientStart", "gradientEnd", "gradientBalance", "gradientContrast"];
|
||||
|
||||
/// The UV Border Distance controls
|
||||
pub const BORDER_DISTANCE_KEYS: [&str; 4] = ["borderDistance", "borderSmoothness", "borderBalance", "borderContrast"];
|
||||
|
||||
/// The Grayscale Conversion controls (its image is the `image` input)
|
||||
pub const GRAYSCALE_KEYS: [&str; 6] = ["grayscaleType", "grayscaleBalance", "grayscaleContrast", "grayscaleTile", "grayscaleRotation", "grayscaleSafeRotation"];
|
||||
|
||||
/// The Dripping Rust controls (it also takes the seed and invert)
|
||||
pub const DRIPPING_RUST_KEYS: [&str; 7] =
|
||||
["rustSpreading", "rustContrast", "spreadingSmoothness", "dripsIntensity", "dripsSmoothness", "dripsSamples", "dripsAxis"];
|
||||
|
||||
/// The UV Random Color controls (it also takes the seed)
|
||||
pub const UV_RANDOM_COLOR_KEYS: [&str; 4] = ["colorSourceMode", "gradientColors", "gradientPositions", "gradientQuantity"];
|
||||
|
||||
/// The UV Checker controls (it also takes the seed)
|
||||
pub const UV_CHECKER_KEYS: [&str; 6] = ["checkerColorMode", "checkerColor", "checkerGridTile", "checkerGridOpacity", "uvBordersColor", "uvBordersWidth"];
|
||||
|
||||
/// The controls of the earlier model and the global adjustments, which these kinds don't have
|
||||
const OTHER_MODEL_KEYS: [&str; 9] = ["level", "softness", "noise", "noiseScale", "offset", "direction", "blur", "balance", "contrast"];
|
||||
|
||||
/// The controls of the kinds with only their own controls in `params`, each refused on other kinds; these kinds refuse the earlier model's and the global controls
|
||||
pub fn distance_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let kind = generator.kind;
|
||||
for (keys, owner) in [
|
||||
(&DISTANCE_KEYS[..], GeneratorKind::ThreeDDistance),
|
||||
(&LINEAR_GRADIENT_KEYS[..], GeneratorKind::ThreeDLinearGradient),
|
||||
(&BORDER_DISTANCE_KEYS[..], GeneratorKind::UvBorderDistance),
|
||||
(&GRAYSCALE_KEYS[..], GeneratorKind::GrayscaleConversion),
|
||||
(&DRIPPING_RUST_KEYS[..], GeneratorKind::DrippingRust),
|
||||
(&UV_RANDOM_COLOR_KEYS[..], GeneratorKind::UvRandomColor),
|
||||
(&UV_CHECKER_KEYS[..], GeneratorKind::UvChecker),
|
||||
] {
|
||||
if let Some(key) = first_given(params, keys).filter(|_| kind != owner) {
|
||||
return Err(bad(command, format!("{} has no `{key}`: only {} has it", kind.label(), owner.label())));
|
||||
}
|
||||
}
|
||||
if !kind.has_no_earlier_model() || kind == GeneratorKind::FiberGlassEdgeWear {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(key) = first_given(params, &OTHER_MODEL_KEYS) {
|
||||
return Err(bad(command, format!("{} has no `{key}`: it has its own controls only", kind.label())));
|
||||
}
|
||||
|
||||
if kind == GeneratorKind::ThreeDLinearGradient {
|
||||
return linear_gradient_from(command, params, generator);
|
||||
}
|
||||
|
||||
if kind == GeneratorKind::GrayscaleConversion {
|
||||
return grayscale_from(command, params, generator);
|
||||
}
|
||||
|
||||
if kind == GeneratorKind::DrippingRust {
|
||||
return dripping_rust_from(command, params, generator);
|
||||
}
|
||||
|
||||
if kind == GeneratorKind::UvRandomColor {
|
||||
return uv_random_color_from(command, params, generator);
|
||||
}
|
||||
|
||||
if kind == GeneratorKind::UvChecker {
|
||||
return uv_checker_from(command, params, generator);
|
||||
}
|
||||
|
||||
if kind == GeneratorKind::UvBorderDistance {
|
||||
let mut border = generator.border_distance_controls().unwrap_or_default();
|
||||
for (key, value) in [
|
||||
("borderDistance", &mut border.distance),
|
||||
("borderSmoothness", &mut border.smoothness),
|
||||
("borderBalance", &mut border.balance),
|
||||
("borderContrast", &mut border.contrast),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::BorderDistance(border.clamped())));
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut distance = generator.distance_controls().unwrap_or_default();
|
||||
for (axis, key) in DISTANCE_KEYS.iter().take(3).enumerate() {
|
||||
if let (Some(value), Some(coordinate)) = (f32p(params, key), distance.point.get_mut(axis)) {
|
||||
*coordinate = value;
|
||||
}
|
||||
}
|
||||
for (key, value) in [("distanceRadius", &mut distance.radius), ("distanceOffset", &mut distance.offset), ("distanceContrast", &mut distance.contrast)] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::Distance(distance.clamped())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The 3D Linear Gradient controls in `params` (the generator is one)
|
||||
fn linear_gradient_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let mut gradient = generator.linear_gradient_controls().unwrap_or_default();
|
||||
if let Some(start) = color_param(command, params, "gradientStart")? {
|
||||
gradient.start = start;
|
||||
}
|
||||
if let Some(end) = color_param(command, params, "gradientEnd")? {
|
||||
gradient.end = end;
|
||||
}
|
||||
for (key, value) in [("gradientBalance", &mut gradient.balance), ("gradientContrast", &mut gradient.contrast)] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::LinearGradient(gradient.clamped())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The Grayscale Conversion controls in `params` (the generator is one)
|
||||
fn grayscale_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let mut grayscale = generator.grayscale_controls().unwrap_or_default();
|
||||
if let Some(value) = params.get("grayscaleType") {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`grayscaleType` must be a string"))?;
|
||||
grayscale.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale type `{name}`")))?;
|
||||
}
|
||||
for (key, value) in [
|
||||
("grayscaleBalance", &mut grayscale.balance),
|
||||
("grayscaleContrast", &mut grayscale.contrast),
|
||||
("grayscaleTile", &mut grayscale.tile),
|
||||
("grayscaleRotation", &mut grayscale.rotation),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
if let Some(safe) = boolp(params, "grayscaleSafeRotation") {
|
||||
grayscale.safe_rotation = safe;
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::Grayscale(grayscale.clamped())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The Dripping Rust controls in `params` (the generator is one)
|
||||
fn dripping_rust_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let Some(KindControls::DrippingRust(mut rust)) = generator.kind_controls() else { return Ok(()) };
|
||||
for (key, value) in [
|
||||
("rustSpreading", &mut rust.spreading),
|
||||
("rustContrast", &mut rust.contrast),
|
||||
("spreadingSmoothness", &mut rust.spreading_smoothness),
|
||||
("dripsIntensity", &mut rust.drips_intensity),
|
||||
("dripsSmoothness", &mut rust.drips_smoothness),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
if let Some(samples) = u64p(params, "dripsSamples") {
|
||||
rust.drips_samples = samples.min(u64::from(DrippingRustParameters::MAX_SAMPLES)) as u32;
|
||||
}
|
||||
if let Some(value) = params.get("dripsAxis") {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`dripsAxis` must be x, y or z"))?;
|
||||
rust.axis = match name.to_ascii_lowercase().as_str() {
|
||||
"x" => 0,
|
||||
"y" => 1,
|
||||
"z" => 2,
|
||||
_ => return Err(bad(command, format!("unknown axis `{name}`: x, y or z"))),
|
||||
};
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::DrippingRust(rust.clamped())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The UV Random Color controls in `params` (the generator is one)
|
||||
fn uv_random_color_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let Some(KindControls::UvRandomColor(mut random)) = generator.kind_controls() else { return Ok(()) };
|
||||
if let Some(value) = params.get("colorSourceMode") {
|
||||
random.custom_gradient = match value.as_str().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("random") => false,
|
||||
Some("customgradient" | "custom gradient" | "gradient") => true,
|
||||
_ => return Err(bad(command, "`colorSourceMode` must be random or customGradient")),
|
||||
};
|
||||
}
|
||||
if let Some(value) = params.get("gradientColors") {
|
||||
let invalid = || bad(command, "`gradientColors` takes 1 to 16 colors, each [r, g, b] or \"#rrggbb\"");
|
||||
let items = value.as_array().filter(|items| (1..=UvRandomColorParameters::MAX_GRADIENT_COLORS).contains(&items.len())).ok_or_else(invalid)?;
|
||||
random.gradient = items.iter().map(|item| color_of(item).ok_or_else(invalid)).collect::<Result<_>>()?;
|
||||
|
||||
// The colors given are the whole gradient: a count after them hides some again
|
||||
random.quantity = None;
|
||||
}
|
||||
if let Some(value) = params.get("gradientPositions") {
|
||||
let invalid = || bad(command, "`gradientPositions` must be numbers in 0..1, at most one per color");
|
||||
let places = value.as_array().filter(|places| places.len() <= random.gradient.len()).ok_or_else(invalid)?;
|
||||
random.positions = places.iter().map(|place| place.as_f64().map(|place| place as f32).ok_or_else(invalid)).collect::<Result<_>>()?;
|
||||
}
|
||||
if params.get("gradientQuantity").is_some() {
|
||||
let range = UvRandomColorParameters::MIN_QUANTITY..=UvRandomColorParameters::MAX_GRADIENT_COLORS as u8;
|
||||
let wanted = u64p(params, "gradientQuantity").and_then(|count| u8::try_from(count).ok()).filter(|count| range.contains(count));
|
||||
let wanted = wanted.ok_or_else(|| bad(command, format!("`gradientQuantity` must be a whole number from {} to {}", range.start(), range.end())))?;
|
||||
random.set_quantity(wanted);
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::UvRandomColor(random.clamped())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The UV Checker controls in `params` (the generator is one)
|
||||
fn uv_checker_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let Some(KindControls::UvChecker(mut checker)) = generator.kind_controls() else { return Ok(()) };
|
||||
if let Some(value) = params.get("checkerColorMode") {
|
||||
checker.random_colors = match value.as_str().map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("uniform") => false,
|
||||
Some("random") => true,
|
||||
_ => return Err(bad(command, "`checkerColorMode` must be uniform or random")),
|
||||
};
|
||||
}
|
||||
if let Some(color) = color_param(command, params, "checkerColor")? {
|
||||
checker.checker_color = color;
|
||||
}
|
||||
if let Some(color) = color_param(command, params, "uvBordersColor")? {
|
||||
checker.border_color = color;
|
||||
}
|
||||
if let Some(tile) = u64p(params, "checkerGridTile") {
|
||||
checker.grid_tile = tile.min(u64::from(*UvCheckerParameters::GRID_TILE_RANGE.end())) as u32;
|
||||
}
|
||||
for (key, value) in [("checkerGridOpacity", &mut checker.grid_opacity), ("uvBordersWidth", &mut checker.border_width)] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
generator.controls = Some(Box::new(KindControls::UvChecker(checker.clamped())));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first of `keys` that `params` gives
|
||||
fn first_given<'a>(params: &Value, keys: &[&'a str]) -> Option<&'a str> {
|
||||
keys.iter().find(|key| params.get(**key).is_some()).copied()
|
||||
}
|
||||
+107
-49
@@ -12,7 +12,9 @@ use serde_json::{Value, json};
|
||||
use texturecraft_core::{NormalFormat, PROJECT_EXT};
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_formats::PlannedFile;
|
||||
use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, primitives};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
|
||||
@@ -26,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New project from a mesh file",
|
||||
[],
|
||||
None,
|
||||
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
|
||||
"{mesh: path to .glb/.gltf/.fbx/.dae/.usd/.usda/.usdc/.usdz/.abc/.obj/.ply/.stl, resolution?: 2048, name?, uvTiles?: bool (UDIM; default: when the UVs leave tile 1001), rebuildUvs?: bool (default false: auto-unwrap where needed), template?: project template name, importCameras?: bool (default true: keep the cameras stored in the file)}",
|
||||
always,
|
||||
new_from_mesh
|
||||
),
|
||||
@@ -101,10 +103,13 @@ fn leaf_of(name: &str) -> String {
|
||||
}
|
||||
|
||||
/// Read the project's stored mesh `bytes` (extension `ext`) under the name it was imported
|
||||
/// with, so its unnamed parts keep their names (and the geometry masks that use them).
|
||||
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8]) -> Result<texturecraft_formats::ImportedMesh> {
|
||||
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|s| s.to_str()).filter(|s| !s.is_empty()).unwrap_or("mesh");
|
||||
texturecraft_formats::import_mesh_bytes(&format!("{stem}.{ext}"), bytes).map_err(fe)
|
||||
/// with, so its unnamed parts keep their names (and the geometry masks that use them). A saved
|
||||
/// UV layout replaces the file's UVs and the automatic unwrap.
|
||||
fn read_stored_mesh(project: &Project, ext: &str, bytes: &[u8], saved_layout: Option<&[Vec2]>) -> Result<Mesh> {
|
||||
let stem = std::path::Path::new(&project.mesh_file).file_stem().and_then(|stem| stem.to_str()).filter(|stem| !stem.is_empty()).unwrap_or("mesh");
|
||||
let file_name = format!("{stem}.{ext}");
|
||||
|
||||
import_mesh_geometry(&file_name, bytes, saved_layout.map_or(MeshUvSource::FromFile, MeshUvSource::Saved)).map_err(fe)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -163,11 +168,16 @@ impl Session {
|
||||
|
||||
/// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]).
|
||||
pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
|
||||
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles)
|
||||
Self::from_mesh_bytes_with_uvs(file_name, bytes, resolution, name, uv_tiles, false)
|
||||
}
|
||||
|
||||
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>) -> Result<Session> {
|
||||
let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?;
|
||||
/// Create a project with an explicit choice to rebuild the imported mesh's UVs.
|
||||
pub fn from_mesh_bytes_with_uvs(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option<bool>, rebuild_uvs: bool) -> Result<Session> {
|
||||
Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles, rebuild_uvs)
|
||||
}
|
||||
|
||||
fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option<bool>, rebuild_uvs: bool) -> Result<Session> {
|
||||
let imported = texturecraft_formats::mesh_import::import_mesh_bytes_with_uvs(file_name, &bytes, rebuild_uvs).map_err(fe)?;
|
||||
let extension = ext_of(file_name);
|
||||
let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?;
|
||||
|
||||
@@ -176,6 +186,7 @@ impl Session {
|
||||
source.shrink_to_fit();
|
||||
session.mesh_source = Some((extension, source));
|
||||
session.doc.project.mesh_file = leaf_of(file_name);
|
||||
session.doc.project.mesh_rebuild_uvs = rebuild_uvs;
|
||||
session.doc.project.cameras = imported.cameras;
|
||||
|
||||
session.log.warnings("Importer", imported.report.warnings);
|
||||
@@ -199,25 +210,39 @@ impl Session {
|
||||
Session::from_project_file(pf)
|
||||
}
|
||||
|
||||
pub fn from_project_file(pf: ProjectFile) -> Result<Session> {
|
||||
let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) {
|
||||
pub fn from_project_file(project_file: ProjectFile) -> Result<Session> {
|
||||
project_file.validate_mesh_uvs().map_err(fe)?;
|
||||
|
||||
let mesh = match (&project_file.mesh, project_file.project.mesh.strip_prefix("builtin:")) {
|
||||
(_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?,
|
||||
(Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh,
|
||||
(Some((ext, bytes)), None) => read_stored_mesh(&project_file.project, ext, bytes, project_file.mesh_uvs.as_deref())?,
|
||||
(None, None) => return Err(EngineError::Other("the project has no mesh".into())),
|
||||
};
|
||||
|
||||
check_materials(&pf.project, &mesh)?;
|
||||
let source = pf.mesh.clone();
|
||||
let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect();
|
||||
let mut s =
|
||||
Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?;
|
||||
// Mesh construction consumed the layout data, so release it before building session caches
|
||||
drop(project_file.mesh_uvs);
|
||||
check_materials(&project_file.project, &mesh)?;
|
||||
let resources = project_file.resources.into_iter().map(|(name, bytes)| (name, Arc::new(bytes))).collect();
|
||||
|
||||
s.sync_images();
|
||||
s.load_bake_meshes(pf.high_poly, pf.cage);
|
||||
s.load_bake_paint(pf.bake_paint);
|
||||
s.log.warnings("Project", pf.warnings);
|
||||
let mut session = Session::new(
|
||||
Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: Default::default(),
|
||||
project: project_file.project,
|
||||
pixels: project_file.pixels,
|
||||
baked: project_file.baked,
|
||||
resources,
|
||||
},
|
||||
mesh,
|
||||
project_file.mesh,
|
||||
)?;
|
||||
|
||||
Ok(s)
|
||||
session.sync_images();
|
||||
session.load_bake_meshes(project_file.high_poly, project_file.cage);
|
||||
session.load_bake_paint(project_file.bake_paint);
|
||||
session.log.warnings("Project", project_file.warnings);
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// The project with independently owned resource bytes.
|
||||
@@ -231,6 +256,11 @@ impl Session {
|
||||
self.project_with_resources(self.doc.resources.clone())
|
||||
}
|
||||
|
||||
/// The layout a project with rebuilt mesh UVs saves, so reopening it never runs the unwrapper.
|
||||
fn saved_uv_layout(&self) -> Option<Vec<Vec2>> {
|
||||
(self.doc.project.mesh_rebuild_uvs && self.mesh_source.is_some()).then(|| texturecraft_formats::mesh_import::corner_uvs(&self.source))
|
||||
}
|
||||
|
||||
fn project_with_resources<Resource>(&self, resources: BTreeMap<String, Resource>) -> ProjectFile<Resource> {
|
||||
let mut pixels = self.doc.pixels.clone();
|
||||
|
||||
@@ -249,11 +279,15 @@ impl Session {
|
||||
pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height())));
|
||||
|
||||
let (high_poly, cage) = self.saved_bake_meshes();
|
||||
let mut project = self.doc.project.clone();
|
||||
project.format_version = project.save_format_version();
|
||||
|
||||
ProjectFile {
|
||||
project: self.doc.project.clone(),
|
||||
project,
|
||||
pixels,
|
||||
baked: self.doc.baked.clone(),
|
||||
mesh: self.mesh_source.clone(),
|
||||
mesh_uvs: self.saved_uv_layout(),
|
||||
high_poly,
|
||||
cage,
|
||||
bake_paint: self.saved_bake_paint(),
|
||||
@@ -519,7 +553,7 @@ mod native {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use native::{absolute, open_path, read_mesh};
|
||||
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the
|
||||
/// `file.new {mesh, name?, resolution?, uvTiles?, rebuildUvs?, template?, importCameras?}`: a new project from the
|
||||
/// mesh file `mesh`, remembering its path for Reimport mesh.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
@@ -530,9 +564,11 @@ fn new_from_mesh(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX);
|
||||
let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
|
||||
let uv_tiles = crate::commands::boolp(params, "uvTiles");
|
||||
let rebuild_uvs = crate::commands::boolp(params, "rebuildUvs").unwrap_or(false);
|
||||
let mesh_file = native::read_mesh("file.new", path)?;
|
||||
|
||||
let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?;
|
||||
let mut next =
|
||||
Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles, rebuild_uvs)?;
|
||||
next.doc.project.mesh_path = native::absolute(path);
|
||||
next.log.warnings("Importer", mesh_file.warnings);
|
||||
if crate::commands::boolp(params, "importCameras") == Some(false) {
|
||||
@@ -595,9 +631,11 @@ fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn change_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = native::path_param(p, "path", "file.changeMesh")?;
|
||||
let file = native::read_mesh("file.changeMesh", path)?;
|
||||
let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?;
|
||||
// Only after the swap succeeded: Reimport mesh and Save keep following the new file.
|
||||
let reply = s.replace_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true), false)?;
|
||||
|
||||
// Keep following the original path if the swap fails
|
||||
s.doc.project.mesh_path = native::absolute(path);
|
||||
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
@@ -608,47 +646,62 @@ impl Session {
|
||||
Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file())
|
||||
}
|
||||
|
||||
/// Replace the mesh with `file` (or re-read the project's own copy) and keep the project:
|
||||
/// texture sets map by material index. Nothing changes unless the new mesh fits the project.
|
||||
/// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies
|
||||
/// like `file.reimportMesh`: `{preserved?}`.
|
||||
/// Replace the mesh with `file` or re-read the project's own copy.
|
||||
/// With `preserve_strokes`, painted pixels follow the surface. The reply includes
|
||||
/// `preserved` when preservation was requested.
|
||||
pub fn reimport_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool) -> Result<Value> {
|
||||
let (mesh, source, warnings, mesh_file) = match file {
|
||||
Some(f) => {
|
||||
let m = texturecraft_formats::import_mesh_bytes(&f.name, &f.bytes).map_err(fe)?.mesh;
|
||||
(m, Some((ext_of(&f.name), f.bytes)), f.warnings, leaf_of(&f.name))
|
||||
self.replace_mesh(file, preserve_strokes, self.doc.project.mesh_rebuild_uvs)
|
||||
}
|
||||
|
||||
fn replace_mesh(&mut self, file: Option<texturecraft_formats::MeshFile>, preserve_strokes: bool, rebuild_uvs: bool) -> Result<Value> {
|
||||
let (mesh, replacement_source, warnings, mesh_file) = match file {
|
||||
Some(file) => {
|
||||
let mesh = import_mesh_geometry(&file.name, &file.bytes, MeshUvSource::from_rebuild_setting(rebuild_uvs)).map_err(fe)?;
|
||||
(mesh, Some((ext_of(&file.name), file.bytes)), file.warnings, leaf_of(&file.name))
|
||||
}
|
||||
None => match &self.mesh_source {
|
||||
Some((ext, bytes)) => {
|
||||
(read_stored_mesh(&self.doc.project, ext, bytes)?.mesh, self.mesh_source.clone(), Vec::new(), self.doc.project.mesh_file.clone())
|
||||
let layout = self.saved_uv_layout();
|
||||
let mesh = read_stored_mesh(&self.doc.project, ext, bytes, layout.as_deref())?;
|
||||
(mesh, None, Vec::new(), self.doc.project.mesh_file.clone())
|
||||
}
|
||||
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
|
||||
},
|
||||
};
|
||||
|
||||
check_materials(&self.doc.project, &mesh)?;
|
||||
let mut doc = self.doc.clone();
|
||||
if let Some((ext, _)) = &source {
|
||||
if let Some((ext, _)) = replacement_source.as_ref().or(self.mesh_source.as_ref()) {
|
||||
doc.project.mesh = format!("mesh.{ext}");
|
||||
doc.project.mesh_file = mesh_file;
|
||||
doc.project.mesh_rebuild_uvs = rebuild_uvs;
|
||||
}
|
||||
let mut next = Session::new(doc, mesh, source)?;
|
||||
|
||||
let mut next = Session::new(doc, mesh, replacement_source)?;
|
||||
next.log.warnings("Importer", warnings);
|
||||
next.path = self.path.clone();
|
||||
next.sync_images();
|
||||
|
||||
// The cage uses triangle indices and barycentrics, so it needs identical geometry
|
||||
next.bake_meshes = self.bake_meshes.clone();
|
||||
next.bake_meshes.low_base_color = Default::default();
|
||||
if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh {
|
||||
next.bake_meshes.cage = None;
|
||||
next.doc.bake_meshes.low_base_color = Default::default();
|
||||
if next.doc.bake_meshes.cage.is_some() && *next.mesh != *self.mesh {
|
||||
next.doc.bake_meshes.cage = None;
|
||||
next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed");
|
||||
}
|
||||
|
||||
if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs {
|
||||
next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode");
|
||||
}
|
||||
|
||||
next.modified = true;
|
||||
next.project_id = self.project_id;
|
||||
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
|
||||
|
||||
// Keep the stored source in the current session until reimport succeeds
|
||||
if next.mesh_source.is_none() {
|
||||
next.mesh_source = self.mesh_source.take();
|
||||
}
|
||||
|
||||
self.switch_to(next);
|
||||
Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n })))
|
||||
}
|
||||
@@ -1486,19 +1539,24 @@ f 1/1 2/2 3/3
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let a = dir.join("a.obj");
|
||||
std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
// Same triangle count, other vertices.
|
||||
|
||||
// Same triangle count, other vertices
|
||||
let b = dir.join("b.obj");
|
||||
std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
|
||||
let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap();
|
||||
let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
|
||||
s.bake_meshes.cage = Some(cage);
|
||||
let _ = s.bake_meshes.low_base_color.set(Err("old".into()));
|
||||
// The same mesh again keeps the cage but not the cached colours.
|
||||
let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
|
||||
s.doc.bake_meshes.cage = Some(cage);
|
||||
let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into()));
|
||||
|
||||
// The same mesh again keeps the cage but not the cached colours
|
||||
crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap();
|
||||
assert!(s.bake_meshes.cage.is_some());
|
||||
assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again");
|
||||
|
||||
assert!(s.doc.bake_meshes.cage.is_some());
|
||||
assert!(s.doc.bake_meshes.low_base_color.get().is_none(), "the colours are read again");
|
||||
|
||||
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
|
||||
assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh");
|
||||
|
||||
assert!(s.doc.bake_meshes.cage.is_none(), "the cage was made for another mesh");
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
use texturecraft_core::BakedMap;
|
||||
|
||||
/// A generator input a command names: a mesh map it reads, its texture or its custom grunge
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum GeneratorInput {
|
||||
Map(BakedMap),
|
||||
Texture,
|
||||
Grunge,
|
||||
MicroHeight,
|
||||
MicroNormal,
|
||||
Image,
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! `effect.generator.pickPoint`: a 3D Distance or 3D Linear Gradient point set from where the mesh is under a viewport point
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{EffectKind, GeneratorKind, LayerId};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, f32p, has_layer, strp, u64p};
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
const CMD: &str = "effect.generator.pickPoint";
|
||||
|
||||
/// The least extent the mesh's bounds count with, so a flat mesh still places a point (the compositor's own floor)
|
||||
const MIN_BOUNDS_EXTENT: f32 = 1e-6;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"effect.generator.pickPoint",
|
||||
"Pick generator point on mesh",
|
||||
[],
|
||||
None,
|
||||
"{effect, point?: distance|start|end (default distance on 3dDistance, start on 3dLinearGradient), x?, y?: viewport pixels (default its centre), viewport?: [w, h]} sets a 3D Distance or 3D Linear Gradient point to the mesh under that pixel, across the mesh's bounds as the generator reads it; returns the point",
|
||||
has_layer,
|
||||
pick_point
|
||||
)]
|
||||
}
|
||||
|
||||
fn pick_point(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let effect = u64p(params, "effect").ok_or_else(|| bad(CMD, "`effect` is required"))?;
|
||||
let kind = match session.doc.project.effect(LayerId(effect)).map(|(_, effect)| &effect.kind) {
|
||||
Some(EffectKind::Generator(generator)) => generator.kind,
|
||||
Some(_) => return Err(bad(CMD, format!("effect {effect} is not a generator"))),
|
||||
None => return Err(bad(CMD, format!("no effect {effect}"))),
|
||||
};
|
||||
let point = strp(params, "point").map(str::to_ascii_lowercase);
|
||||
let key = match (kind, point.as_deref()) {
|
||||
(GeneratorKind::ThreeDDistance, None | Some("distance")) => "distance",
|
||||
(GeneratorKind::ThreeDLinearGradient, None | Some("start")) => "gradientStart",
|
||||
(GeneratorKind::ThreeDLinearGradient, Some("end")) => "gradientEnd",
|
||||
(GeneratorKind::ThreeDDistance | GeneratorKind::ThreeDLinearGradient, Some(other)) => {
|
||||
return Err(bad(CMD, format!("{} has no point `{other}`", kind.label())));
|
||||
}
|
||||
_ => return Err(bad(CMD, format!("{} has no point to pick: only 3D Distance and 3D Linear Gradient have one", kind.label()))),
|
||||
};
|
||||
|
||||
let viewport = viewport_of(session, params);
|
||||
let screen = match (f32p(params, "x"), f32p(params, "y")) {
|
||||
(Some(x), Some(y)) => Vec2::new(x, y),
|
||||
(None, None) => viewport * 0.5,
|
||||
_ => return Err(bad(CMD, "give both `x` and `y`, or neither for the viewport's centre")),
|
||||
};
|
||||
let hit = session.pick(screen, viewport).ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?;
|
||||
let picked = across_bounds(hit.pos, session.mesh.bounds()).to_array().map(|coordinate| coordinate.clamp(0.0, 1.0));
|
||||
|
||||
let edit = match key {
|
||||
"distance" => json!({"effect": effect, "distanceX": picked[0], "distanceY": picked[1], "distanceZ": picked[2]}),
|
||||
_ => json!({"effect": effect, key: picked}),
|
||||
};
|
||||
crate::mask_cmds::set(session, &edit)?;
|
||||
Ok(json!({"effect": effect, "point": picked}))
|
||||
}
|
||||
|
||||
/// `position` across `bounds` as the 3D generators read the mesh: scaled evenly by the longest side, centred on 0.5
|
||||
pub fn across_bounds(position: Vec3, (low, high): (Vec3, Vec3)) -> Vec3 {
|
||||
let longest = (high - low).max_element().max(MIN_BOUNDS_EXTENT);
|
||||
(position - (low + high) * 0.5) / longest + Vec3::splat(0.5)
|
||||
}
|
||||
@@ -153,13 +153,31 @@ fn generator_json(generator: &Generator) -> Value {
|
||||
if !generator.inputs.is_empty() {
|
||||
out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::<serde_json::Map<_, _>>().into();
|
||||
}
|
||||
if let Some(wear) = &generator.wear {
|
||||
out["wear"] = json!(wear);
|
||||
}
|
||||
if let Some(section) = &generator.section {
|
||||
out["section"] = json!(section);
|
||||
}
|
||||
if let Some(light) = &generator.light {
|
||||
out["light"] = json!(light);
|
||||
}
|
||||
if let Some(texture) = &generator.texture {
|
||||
out["texture"] = json!(texture);
|
||||
}
|
||||
if let Some(grunge) = &generator.grunge {
|
||||
out["grunge"] = source_json(grunge);
|
||||
}
|
||||
if let Some(micro) = &generator.micro {
|
||||
out["micro"] = json!(micro);
|
||||
}
|
||||
if let Some(controls) = &generator.controls {
|
||||
out["controls"] = json!(controls);
|
||||
}
|
||||
if let Some(detail) = &generator.detail {
|
||||
out["mode"] = json!(format!("{:?}", detail.mode));
|
||||
out["sizes"] = json!(detail.weights);
|
||||
}
|
||||
if let Some(micro) = &generator.micro {
|
||||
out["micro"] = json!({ "anchor": micro.anchor.0, "amount": micro.amount });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod add_mask_cmds;
|
||||
mod anchored_micro_edit;
|
||||
pub mod bake;
|
||||
pub mod bake_preview;
|
||||
pub mod brush_preset_cmds;
|
||||
@@ -16,6 +17,7 @@ pub mod camera_cmds;
|
||||
pub mod color_selection_cmds;
|
||||
pub mod commands;
|
||||
pub mod decal_cmds;
|
||||
pub mod distance_params;
|
||||
pub mod effect_blending_cmds;
|
||||
pub mod effect_clipboard;
|
||||
pub mod file_cmds;
|
||||
@@ -28,6 +30,8 @@ pub mod filter_about;
|
||||
pub mod filter_lib;
|
||||
pub mod folder_cmds;
|
||||
mod frame_target;
|
||||
mod generator_input;
|
||||
pub mod generator_pick;
|
||||
pub mod id_mask_view;
|
||||
pub mod inspect;
|
||||
pub mod instance_cmds;
|
||||
@@ -50,6 +54,7 @@ pub mod materialx_cmds;
|
||||
pub mod meshmap_cmds;
|
||||
mod meshmap_file_name;
|
||||
pub mod meshmap_import_cmds;
|
||||
pub mod micro_params;
|
||||
mod orb_camera;
|
||||
pub mod orb_preview;
|
||||
pub mod painting;
|
||||
@@ -83,14 +88,13 @@ mod tile_transform_params;
|
||||
mod tool_availability;
|
||||
pub mod tool_cmds;
|
||||
pub mod tool_settings;
|
||||
mod triangle_partition;
|
||||
mod uv_stroke_state;
|
||||
mod uv_symmetry;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
pub mod warp_cmds;
|
||||
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap};
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask, HighPolyLoad, StreamedBake, StreamedMap};
|
||||
pub use bake_preview::{BakePreview, PreviewShow};
|
||||
pub use commands::{CommandSpec, check_enabled, command_specs, execute, find};
|
||||
pub use fill_hit_test::FillHitTest;
|
||||
|
||||
+436
-61
@@ -2,13 +2,18 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator,
|
||||
GeneratorKind, LayerId, Levels, Mask, MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Sampling, Source,
|
||||
AxisBlend, BakedMap, BlendMode, Channel, ChannelKind, ColorSelection, CompareOp, CompareSource, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter,
|
||||
Generator, GeneratorGrayscale, GeneratorKind, KindControls, LayerId, Levels, LightParameters, Mask, MaskBackground, Procedural, ProceduralKind, Project,
|
||||
Sampling, SectionParameters, Source, TextureBlend, WearParameters,
|
||||
};
|
||||
|
||||
use crate::anchored_micro_edit::AnchoredMicroEdit;
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
use crate::distance_params::distance_from;
|
||||
use crate::generator_input::GeneratorInput;
|
||||
use crate::layer_cmds::{projection_from, projection_from_fields};
|
||||
use crate::mask_owner::MaskOwner;
|
||||
use crate::micro_params::{MICRO_HEIGHT_INPUT, MICRO_NORMAL_INPUT, micro_from, swapped_micro};
|
||||
use crate::session::StackTarget;
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
@@ -28,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_layer,
|
||||
add_color_mask
|
||||
),
|
||||
cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?}", has_layer, toggle),
|
||||
cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?} — defaults to the selected layer", always, toggle),
|
||||
cmd!("mask.invertBackground", "Invert mask background", ["Layers", "Mask"], None, "{layer?}", has_layer, invert_background),
|
||||
cmd!("mask.invert", "Invert mask", ["Layers", "Mask"], None, "{layer?}", has_layer, invert),
|
||||
cmd!("mask.clear", "Clear mask", ["Layers", "Mask"], None, "{layer?}", has_layer, clear),
|
||||
@@ -53,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add generator",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below, microAmount?: 0..1 (0.5)}",
|
||||
"{layer?, name?, generator?: edgeWear|dirt|fiberGlassEdgeWear|thinAreas|curvature|ambientOcclusion|position|worldSpaceNormals|direction|3dDistance|3dLinearGradient|uvBorderDistance|grayscaleConversion|drippingRust|uvRandomColor|uvChecker, wearLevel?, wearContrast?, grungeAmount?, grungeScale?: 1..16, triplanar?, triplanarContrast?, edgesSmoothness?: 0..16, aoMasking?, curvatureWeight?, edgesMasking?, useCustomGrunge? (the image: effect.set input: grunge) (wear controls: edgeWear, fiberGlassEdgeWear and dirt), sectionInvert?, sectionBlur?: 0..16 (ambientOcclusion, worldSpaceNormals), sectionBalance? (not curvature), sectionContrast?, sectionBrightness?: -1..1 (not ambientOcclusion), rightLeft|topBottom|frontBack + Invert?|Blend?: normal|add|subtract|multiply|addSub|max|Weight? (position, worldSpaceNormals), useTexture?, textureOpacity?, textureInvert?, textureGrayscale?: desaturation|luma|average|max|min|red|green|blue, textureBlend?: normal|add|subtract|multiply|addSub|max|min|overlay|screen|softLight, textureScale?: 0.01..10, textureContrast?: -1..1, textureBrightness?: -1..1, textureTriplanar?, textureTriplanarContrast? (the texture itself: effect.set input: texture) (section controls: curvature, ambientOcclusion, position, worldSpaceNormals), useMicroDetails? (curvature, ambientOcclusion), microHeight?, microNormal? (the images: effect.set input: microHeight|microNormal, an image or a value; microHeight also an anchor point), microCurvatureType?: standard|sobel|smooth, microCurvatureIntensity?: 0..5 on curvature, 0..1 on the wear kinds, microHeightIntensity?: 0..10 (curvature and the wear kinds), microAoRadius?, microAoDepth? (ambientOcclusion and the wear kinds) (micro details), distanceX?, distanceY?, distanceZ? (the point across the mesh's bounds), distanceRadius?: 0..1.5, distanceOffset? (0 all black, 1 all white), distanceContrast? (3dDistance, which also takes invert), gradientStart?, gradientEnd?: [x, y, z] across the mesh's bounds, gradientBalance?, gradientContrast? (3dLinearGradient, which also takes invert), borderDistance? (1 = half a UV tile), borderSmoothness?, borderBalance?, borderContrast? (uvBorderDistance, which also takes invert), grayscaleType?: desaturation|luma|average|max|min|red|green|blue, grayscaleBalance?, grayscaleContrast?, grayscaleTile?: 1..16, grayscaleRotation?: 0..360, grayscaleSafeRotation? (grayscaleConversion, which also takes invert; its image: effect.set input: image), rustSpreading?, rustContrast?, spreadingSmoothness?, dripsIntensity?, dripsSmoothness?, dripsSamples?: 0..32, dripsAxis?: x|y|z (drippingRust, which also takes seed and invert), colorSourceMode?: random|customGradient, gradientColors?: [[r,g,b], ...], gradientPositions?: [0..1 per color], gradientQuantity?: 2..16 (uvRandomColor, which also takes seed), checkerColorMode?: uniform|random, checkerColor?, checkerGridTile?: 1..24, checkerGridOpacity?, uvBordersColor?, uvBordersWidth? (uvChecker, which also takes seed), lightHorizontal?: 0..360, lightVertical?: 0..360, highlightGlossiness?, highlightLevel?, lightAttenuation? (light controls: direction), level?, softness?, noise?, noiseScale?, offset?: -1..1 added to the result, direction? (instead keep edgeWear, dirt, curvature, ambientOcclusion, position and direction on the earlier model), invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as the Micro Height), microAmount?: 0..1 (the Micro Height's intensity, 0.5 = 1)}",
|
||||
has_layer,
|
||||
add_generator
|
||||
),
|
||||
@@ -98,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit effect",
|
||||
[],
|
||||
None,
|
||||
"{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}",
|
||||
"{effect, visible?, blend?, opacity?, channel?: the content channel blend and opacity set (default: every channel), name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place; \"none\" empties it), channels?: {channelId: bool} a content effect's channels on or off, divider?: 1|10|100|1000 (warp, slope blur: divides the intensity), generator?: kind (a generator effect only: swaps its kind in place, keeping the shared settings and the inputs it reads; its own controls start from that kind's defaults), wear, section and light controls (see effect.add.generator), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id, texture, grunge, microHeight, microNormal or image + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null (the Micro Height reads that anchor point; null empties it), microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, affects?, clamp? (levels), tolerance?, left?, op?, right?, compareChannel?, hardness? (compare; value is its constant), colors?: [[r,g,b] linear, ...] (a color selection's ID colors, may be empty), output?, background?: transparent | black | white | gray, idMap?: an image resource name read as the ID map, null for the texture set's ID mesh map (a color selection; tolerance and hardness too), filter parameters (see effect.add.filter)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -127,6 +132,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
fn with_mask<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnce(&mut Session, LayerId) -> Result<T>) -> Result<T> {
|
||||
let id = layer_param(s, cmd, p)?;
|
||||
|
||||
s.edit(label, |s| f(s, id))
|
||||
}
|
||||
|
||||
@@ -169,13 +175,14 @@ fn mask_of(s: &mut Session, id: LayerId) -> Result<&mut Mask> {
|
||||
l.mask.as_mut().ok_or_else(|| EngineError::Other(format!("\"{name}\" has no mask")))
|
||||
}
|
||||
|
||||
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = with_mask(s, p, "mask.toggle", "Toggle mask", |s, id| {
|
||||
let m = mask_of(s, id)?;
|
||||
m.enabled = boolp(p, "enabled").unwrap_or(!m.enabled);
|
||||
Ok(m.enabled)
|
||||
fn toggle(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let enabled = with_mask(session, params, "mask.toggle", "Toggle mask", |session, layer| {
|
||||
let mask = mask_of(session, layer)?;
|
||||
mask.enabled = boolp(params, "enabled").unwrap_or(!mask.enabled);
|
||||
Ok(mask.enabled)
|
||||
})?;
|
||||
Ok(json!({ "enabled": on }))
|
||||
|
||||
Ok(json!({ "enabled": enabled }))
|
||||
}
|
||||
|
||||
fn invert_background(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -387,8 +394,327 @@ fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
push_effect(session, params, EffectKind::Fill { source, projection, sampling }, blend)
|
||||
}
|
||||
|
||||
/// The parameters that drive the wear generators' earlier model
|
||||
const EARLIER_WEAR_KEYS: [&str; 7] = ["level", "softness", "noise", "noiseScale", "offset", "mode", "sizes"];
|
||||
|
||||
/// The global adjustments, which the wear kinds don't have
|
||||
const GLOBAL_KEYS: [&str; 3] = ["blur", "balance", "contrast"];
|
||||
|
||||
/// The wear controls `effect.add.generator` and `effect.set` take
|
||||
const WEAR_KEYS: [&str; 11] = [
|
||||
"wearLevel",
|
||||
"wearContrast",
|
||||
"grungeAmount",
|
||||
"grungeScale",
|
||||
"triplanar",
|
||||
"triplanarContrast",
|
||||
"edgesSmoothness",
|
||||
"aoMasking",
|
||||
"curvatureWeight",
|
||||
"edgesMasking",
|
||||
"useCustomGrunge",
|
||||
];
|
||||
|
||||
/// The input name of a wear generator's custom grunge image, beside the mesh map ids
|
||||
const GRUNGE_INPUT: &str = "grunge";
|
||||
|
||||
/// The wear controls in `params` (a grunge input counts as one): they move a wear generator onto them, while level, softness, noise or offset keep it on the earlier model
|
||||
fn wear_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some());
|
||||
let wear_given = given(&WEAR_KEYS) || strp(params, "input") == Some(GRUNGE_INPUT);
|
||||
let Some(defaults) = WearParameters::defaults(generator.kind) else {
|
||||
return if wear_given { Err(bad(command, format!("{} has no wear controls", generator.kind.label()))) } else { Ok(()) };
|
||||
};
|
||||
|
||||
let earlier_model = given(&EARLIER_WEAR_KEYS) || (generator.wear.is_none() && !wear_given && generator.kind != GeneratorKind::FiberGlassEdgeWear);
|
||||
if given(&GLOBAL_KEYS) && !earlier_model {
|
||||
return Err(bad(command, format!("{} has no global blur, balance or contrast on its wear controls", generator.kind.label())));
|
||||
}
|
||||
|
||||
if let Some(unused) = WEAR_KEYS.iter().find(|key| params.get(**key).is_some() && !wear_key_applies(generator.kind, key)) {
|
||||
return Err(bad(command, format!("{} has no `{unused}`", generator.kind.label())));
|
||||
}
|
||||
|
||||
if given(&EARLIER_WEAR_KEYS) {
|
||||
if wear_given {
|
||||
return Err(bad(command, "level, softness, noise and offset drive the earlier wear model: give them or the wear controls, not both"));
|
||||
}
|
||||
|
||||
if generator.kind == GeneratorKind::FiberGlassEdgeWear {
|
||||
return Err(bad(command, format!("{} requires wear controls such as wearLevel or wearContrast", generator.kind.label())));
|
||||
}
|
||||
generator.wear = None;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !wear_given {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// The offset belongs to the earlier model: kept, it would shift the wear controls' result unseen
|
||||
generator.offset = 0.0;
|
||||
let wear = generator.wear.get_or_insert(defaults);
|
||||
for (key, value) in [
|
||||
("wearLevel", &mut wear.level),
|
||||
("wearContrast", &mut wear.contrast),
|
||||
("grungeAmount", &mut wear.grunge_amount),
|
||||
("grungeScale", &mut wear.grunge_scale),
|
||||
("triplanarContrast", &mut wear.triplanar_contrast),
|
||||
("edgesSmoothness", &mut wear.edges_smoothness),
|
||||
("aoMasking", &mut wear.ao_masking),
|
||||
("curvatureWeight", &mut wear.curvature_weight),
|
||||
("edgesMasking", &mut wear.edges_masking),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
if let Some(triplanar) = boolp(params, "triplanar") {
|
||||
wear.triplanar = triplanar;
|
||||
}
|
||||
if let Some(custom_grunge) = boolp(params, "useCustomGrunge") {
|
||||
wear.custom_grunge = custom_grunge;
|
||||
}
|
||||
*wear = wear.clamped(generator.kind);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether wear control `key` changes a generator of `kind`
|
||||
pub fn wear_key_applies(kind: GeneratorKind, key: &str) -> bool {
|
||||
match key {
|
||||
"edgesMasking" => kind == GeneratorKind::Dirt,
|
||||
"edgesSmoothness" | "aoMasking" | "curvatureWeight" => kind != GeneratorKind::Dirt,
|
||||
"grungeScale" => kind != GeneratorKind::FiberGlassEdgeWear,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters that drive the earlier model of the kinds with section or light controls
|
||||
const EARLIER_SECTION_KEYS: [&str; 6] = ["level", "softness", "noise", "noiseScale", "offset", "direction"];
|
||||
|
||||
/// The section controls `effect.add.generator` and `effect.set` take, beside the axis keys made of [`AXIS_NAMES`] and [`AXIS_SUFFIXES`]
|
||||
const SECTION_KEYS: [&str; 5] = ["sectionInvert", "sectionBlur", "sectionBalance", "sectionContrast", "sectionBrightness"];
|
||||
|
||||
/// The name of each axis in its keys, in the order of [`SectionParameters::axes`], and what follows it
|
||||
const AXIS_NAMES: [&str; 3] = ["rightLeft", "topBottom", "frontBack"];
|
||||
const AXIS_SUFFIXES: [&str; 3] = ["Invert", "Blend", "Weight"];
|
||||
|
||||
/// The Light generator's controls
|
||||
const LIGHT_KEYS: [&str; 5] = ["lightHorizontal", "lightVertical", "highlightGlossiness", "highlightLevel", "lightAttenuation"];
|
||||
|
||||
/// The texture controls (Use Texture); the texture itself is the `texture` input
|
||||
const TEXTURE_KEYS: [&str; 10] = [
|
||||
"useTexture",
|
||||
"textureOpacity",
|
||||
"textureInvert",
|
||||
"textureGrayscale",
|
||||
"textureBlend",
|
||||
"textureScale",
|
||||
"textureContrast",
|
||||
"textureBrightness",
|
||||
"textureTriplanar",
|
||||
"textureTriplanarContrast",
|
||||
];
|
||||
|
||||
/// The input name of Grayscale Conversion's image, beside the mesh map ids
|
||||
const GRAYSCALE_IMAGE_INPUT: &str = "image";
|
||||
|
||||
/// The input name of a generator's texture, beside the mesh map ids
|
||||
const TEXTURE_INPUT: &str = "texture";
|
||||
|
||||
/// The section controls, the axis keys, the texture controls and the light controls `params` gives (a texture input counts as `texture`)
|
||||
fn given_new_model_keys(params: &Value) -> Vec<String> {
|
||||
let axis_keys = AXIS_NAMES.iter().flat_map(|axis| AXIS_SUFFIXES.iter().map(move |suffix| format!("{axis}{suffix}")));
|
||||
let mut keys: Vec<String> = SECTION_KEYS
|
||||
.iter()
|
||||
.chain(TEXTURE_KEYS.iter())
|
||||
.chain(LIGHT_KEYS.iter())
|
||||
.map(|key| key.to_string())
|
||||
.chain(axis_keys)
|
||||
.filter(|key| params.get(key).is_some())
|
||||
.collect();
|
||||
if strp(params, "input") == Some(TEXTURE_INPUT) {
|
||||
keys.push(TEXTURE_INPUT.to_string());
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
/// The section and light controls in `params`: they move a generator onto them, while level, softness, noise, offset or direction keep it on the earlier model
|
||||
fn section_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
let kind = generator.kind;
|
||||
let new_keys = given_new_model_keys(params);
|
||||
let earlier = EARLIER_SECTION_KEYS.iter().any(|key| params.get(*key).is_some());
|
||||
let section_defaults = SectionParameters::defaults(kind);
|
||||
let light_defaults = LightParameters::defaults(kind);
|
||||
if section_defaults.is_none() && light_defaults.is_none() {
|
||||
return match new_keys.first() {
|
||||
Some(key) => Err(bad(
|
||||
command,
|
||||
format!("{} has no `{key}`: only Curvature, Ambient Occlusion, Position, World Space Normals and Light have them", kind.label()),
|
||||
)),
|
||||
None => Ok(()),
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(unused) = new_keys.iter().find(|key| !section_key_applies(kind, key)) {
|
||||
return Err(bad(command, format!("{} has no `{unused}`", kind.label())));
|
||||
}
|
||||
|
||||
let reads_direction = matches!(kind, GeneratorKind::Position | GeneratorKind::Direction);
|
||||
if params.get("direction").is_some() && !reads_direction {
|
||||
return Err(bad(command, format!("{} has no `direction`: only Position and Light point one way", kind.label())));
|
||||
}
|
||||
|
||||
if earlier {
|
||||
if !new_keys.is_empty() {
|
||||
return Err(bad(
|
||||
command,
|
||||
"level, softness, noise, offset and direction drive the earlier model: give them or the section and light controls, not both",
|
||||
));
|
||||
}
|
||||
if kind == GeneratorKind::WorldSpaceNormals {
|
||||
return Err(bad(
|
||||
command,
|
||||
"World Space Normals has section controls only (sectionBalance, topBottomWeight…), no level, softness, noise, offset or direction",
|
||||
));
|
||||
}
|
||||
generator.section = None;
|
||||
generator.light = None;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let on_light = generator.light.is_some() || (light_defaults.is_some() && !new_keys.is_empty());
|
||||
if on_light && GLOBAL_KEYS.iter().any(|key| params.get(*key).is_some()) {
|
||||
return Err(bad(command, "Light has no global blur, balance or contrast on its light controls"));
|
||||
}
|
||||
|
||||
if new_keys.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Moving onto the reference's controls starts from the kind's defaults: the earlier model's values no longer apply
|
||||
if generator.on_earlier_model() {
|
||||
let defaults = Generator::new(kind);
|
||||
(generator.level, generator.softness, generator.noise_amount, generator.noise_scale) =
|
||||
(defaults.level, defaults.softness, defaults.noise_amount, defaults.noise_scale);
|
||||
(generator.offset, generator.direction) = (defaults.offset, defaults.direction);
|
||||
if light_defaults.is_some() {
|
||||
generator.global = defaults.global;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(defaults) = light_defaults {
|
||||
let light = generator.light.get_or_insert(defaults);
|
||||
for (key, value) in [
|
||||
("lightHorizontal", &mut light.horizontal),
|
||||
("lightVertical", &mut light.vertical),
|
||||
("highlightGlossiness", &mut light.glossiness),
|
||||
("highlightLevel", &mut light.highlight_level),
|
||||
("lightAttenuation", &mut light.attenuation),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
*light = light.clamped();
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(defaults) = section_defaults else { return Ok(()) };
|
||||
let mut section = generator.section_controls().unwrap_or(defaults);
|
||||
for (key, value) in [
|
||||
("sectionBlur", &mut section.blur),
|
||||
("sectionBalance", &mut section.balance),
|
||||
("sectionContrast", &mut section.contrast),
|
||||
("sectionBrightness", &mut section.brightness),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(invert) = boolp(params, "sectionInvert") {
|
||||
section.invert = invert;
|
||||
}
|
||||
|
||||
for (axis, name) in section.axes.iter_mut().zip(AXIS_NAMES) {
|
||||
if let Some(invert) = boolp(params, &format!("{name}Invert")) {
|
||||
axis.invert = invert;
|
||||
}
|
||||
if let Some(weight) = f32p(params, &format!("{name}Weight")) {
|
||||
axis.weight = weight;
|
||||
}
|
||||
let blend_key = format!("{name}Blend");
|
||||
if let Some(blend) = params.get(&blend_key) {
|
||||
let blend_name = blend.as_str().ok_or_else(|| bad(command, format!("`{blend_key}` must be a string")))?;
|
||||
axis.blend = AxisBlend::parse(blend_name).ok_or_else(|| bad(command, format!("unknown blending mode `{blend_name}`")))?;
|
||||
}
|
||||
}
|
||||
|
||||
generator.section = Some(section.clamped(kind));
|
||||
texture_from(command, params, generator)
|
||||
}
|
||||
|
||||
/// The texture controls in `params` (the generator is on its section controls already)
|
||||
fn texture_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
if !TEXTURE_KEYS.iter().any(|key| params.get(*key).is_some()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut texture = generator.texture.as_deref().cloned().unwrap_or_default();
|
||||
if let Some(enabled) = boolp(params, "useTexture") {
|
||||
texture.enabled = enabled;
|
||||
}
|
||||
for (key, value) in [
|
||||
("textureOpacity", &mut texture.opacity),
|
||||
("textureScale", &mut texture.scale),
|
||||
("textureContrast", &mut texture.contrast),
|
||||
("textureBrightness", &mut texture.brightness),
|
||||
("textureTriplanarContrast", &mut texture.triplanar_contrast),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
if let Some(invert) = boolp(params, "textureInvert") {
|
||||
texture.invert = invert;
|
||||
}
|
||||
if let Some(triplanar) = boolp(params, "textureTriplanar") {
|
||||
texture.triplanar = triplanar;
|
||||
}
|
||||
if let Some(value) = params.get("textureGrayscale") {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`textureGrayscale` must be a string"))?;
|
||||
texture.grayscale = GeneratorGrayscale::parse(name).ok_or_else(|| bad(command, format!("unknown grayscale conversion `{name}`")))?;
|
||||
}
|
||||
if let Some(value) = params.get("textureBlend") {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`textureBlend` must be a string"))?;
|
||||
texture.blend = TextureBlend::parse(name).ok_or_else(|| bad(command, format!("unknown blending mode `{name}`")))?;
|
||||
}
|
||||
generator.texture = Some(Box::new(texture.clamped()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether section or light control `key` changes a generator of `kind`
|
||||
pub fn section_key_applies(kind: GeneratorKind, key: &str) -> bool {
|
||||
let axis_key = AXIS_NAMES.iter().any(|axis| key.strip_prefix(axis).is_some_and(|suffix| AXIS_SUFFIXES.contains(&suffix)));
|
||||
match key {
|
||||
"sectionInvert" | "sectionContrast" | TEXTURE_INPUT => SectionParameters::defaults(kind).is_some(),
|
||||
_ if TEXTURE_KEYS.contains(&key) => SectionParameters::defaults(kind).is_some(),
|
||||
"sectionBlur" => SectionParameters::has_blur(kind),
|
||||
"sectionBalance" => SectionParameters::has_balance(kind),
|
||||
"sectionBrightness" => SectionParameters::has_brightness(kind),
|
||||
_ if axis_key => SectionParameters::has_axes(kind),
|
||||
_ => LIGHT_KEYS.contains(&key) && LightParameters::defaults(kind).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `params` to `generator`, using `command` in errors
|
||||
fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
wear_from(command, params, generator)?;
|
||||
section_from(command, params, generator)?;
|
||||
let earlier_keys: &[&str] = if WearParameters::defaults(generator.kind).is_some() { &EARLIER_WEAR_KEYS } else { &EARLIER_SECTION_KEYS };
|
||||
micro_from(command, params, generator, earlier_keys)?;
|
||||
distance_from(command, params, generator)?;
|
||||
if let Some(level) = f32p(params, "level") {
|
||||
generator.level = level.clamp(0.0, 1.0);
|
||||
}
|
||||
@@ -478,43 +804,19 @@ fn add_anchor(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
push_effect(session, &Value::Object(fields), EffectKind::Anchor, BlendMode::Normal)
|
||||
}
|
||||
|
||||
/// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer
|
||||
/// `reader` (None: leave it as it is; `Some(None)`: remove it).
|
||||
fn micro_param(session: &Session, command: &str, reader: LayerId, params: &Value, current: Option<MicroDetail>) -> Result<Option<Option<MicroDetail>>> {
|
||||
let amount = match params.get("microAmount") {
|
||||
Some(value) => {
|
||||
Some(value.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(command, "`microAmount` must be a number 0..1"))?.clamp(0.0, 1.0) as f32)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let anchor = match params.get("microAnchor") {
|
||||
None => current.map(|m| m.anchor),
|
||||
Some(Value::Null) => return Ok(Some(None)),
|
||||
Some(value) => Some(LayerId(value.as_u64().ok_or_else(|| bad(command, "`microAnchor` must be an anchor effect id or null"))?)),
|
||||
};
|
||||
let Some(anchor) = anchor else {
|
||||
return match amount {
|
||||
Some(_) => Err(bad(command, "give `microAnchor` before `microAmount`: the generator has no micro detail")),
|
||||
None => Ok(None),
|
||||
};
|
||||
};
|
||||
|
||||
if params.get("microAnchor").is_none() && amount.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// The same rule as fills: an anchor below, in the same texture set
|
||||
anchor_source(session, command, reader, anchor, Channel::Height)?;
|
||||
let amount = amount.or(current.map(|m| m.amount)).unwrap_or(MicroDetail::DEFAULT_AMOUNT);
|
||||
Ok(Some(Some(MicroDetail { anchor, amount })))
|
||||
}
|
||||
|
||||
/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`.
|
||||
fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result<Option<(BakedMap, Option<Source>)>> {
|
||||
/// The generator input named by `input` and what replaces it (None: its mesh map again, or an empty texture or grunge slot), for a generator on layer `owner`
|
||||
fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result<Option<(GeneratorInput, Option<Source>)>> {
|
||||
const CMD: &str = "effect.set";
|
||||
let Some(name) = params.get("input") else { return Ok(None) };
|
||||
let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?;
|
||||
let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?;
|
||||
let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id, `texture`, `grunge`, `microHeight`, `microNormal` or `image`"))?;
|
||||
let input = match name {
|
||||
TEXTURE_INPUT => GeneratorInput::Texture,
|
||||
GRUNGE_INPUT => GeneratorInput::Grunge,
|
||||
MICRO_HEIGHT_INPUT => GeneratorInput::MicroHeight,
|
||||
MICRO_NORMAL_INPUT => GeneratorInput::MicroNormal,
|
||||
GRAYSCALE_IMAGE_INPUT => GeneratorInput::Image,
|
||||
_ => GeneratorInput::Map(BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?),
|
||||
};
|
||||
|
||||
let image = strp(params, "inputImage");
|
||||
let value = f32p(params, "inputValue");
|
||||
@@ -525,9 +827,13 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R
|
||||
if !session.images.contains_key(image) {
|
||||
return Err(bad(CMD, format!("no image resource `{image}`")));
|
||||
}
|
||||
|
||||
Some(Source::Image { name: image.to_string(), normal_format: Default::default() })
|
||||
}
|
||||
(None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])),
|
||||
(None, None, Some(_), false) if matches!(input, GeneratorInput::MicroNormal) => {
|
||||
return Err(bad(CMD, "the micro normal reads an image or a value, not an anchor point"));
|
||||
}
|
||||
(None, None, Some(anchor), false) => {
|
||||
let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height);
|
||||
Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?)
|
||||
@@ -535,7 +841,7 @@ fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> R
|
||||
(None, None, None, true) => None,
|
||||
_ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")),
|
||||
};
|
||||
Ok(Some((map, source)))
|
||||
Ok(Some((input, source)))
|
||||
}
|
||||
|
||||
fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
@@ -547,8 +853,8 @@ fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
generator_from("effect.add.generator", params, &mut generator)?;
|
||||
let selected_layer = layer_param(session, "effect.add.generator", params)?;
|
||||
let reader = session.doc.project.mask_owner(selected_layer);
|
||||
if let Some(micro) = micro_param(session, "effect.add.generator", reader, params, None)? {
|
||||
generator.micro = micro;
|
||||
if let Some(edit) = AnchoredMicroEdit::parse(session, "effect.add.generator", reader, params)? {
|
||||
edit.apply("effect.add.generator", &mut generator)?;
|
||||
}
|
||||
let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal);
|
||||
push_effect(session, params, EffectKind::Generator(generator), blend)
|
||||
@@ -714,7 +1020,7 @@ fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// Edit visibility, blending, name, effect parameters, or a filter's type
|
||||
fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
pub(crate) fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.set";
|
||||
let effect = effect_id(session, params, CMD)?;
|
||||
let blend = blend_param(CMD, params, "blend")?;
|
||||
@@ -757,7 +1063,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
};
|
||||
|
||||
let micro = match session.doc.project.effect(effect) {
|
||||
Some((owner, Effect { kind: EffectKind::Generator(generator), .. })) => micro_param(session, CMD, owner, params, generator.micro)?,
|
||||
Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => AnchoredMicroEdit::parse(session, CMD, owner, params)?,
|
||||
_ if params.get("microAnchor").is_some() || params.get("microAmount").is_some() => {
|
||||
return Err(bad(CMD, "`microAnchor` and `microAmount` edit generator effects only"));
|
||||
}
|
||||
@@ -785,10 +1091,17 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
};
|
||||
let swaps_filter = swapped.is_some();
|
||||
let id_map = crate::color_selection_cmds::id_map_param(session, params)?;
|
||||
let swapped_generator = match strp(params, "generator") {
|
||||
Some(kind) => swapped_generator_kind(session, effect, kind)?,
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mesh = session.mesh.clone();
|
||||
session.edit("Edit effect", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let Some(generator) = swapped_generator {
|
||||
edited.kind = EffectKind::Generator(generator);
|
||||
}
|
||||
if let Some((kind, label)) = swapped {
|
||||
if let EffectKind::Filter(old) = &edited.kind
|
||||
&& (edited.name == old.label() || Some(edited.name.as_str()) == old.former_label())
|
||||
@@ -823,18 +1136,45 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
generator.inputs.retain(|map, _| kind.inputs().contains(map));
|
||||
}
|
||||
generator_from(CMD, params, generator)?;
|
||||
if let Some(micro) = micro {
|
||||
generator.micro = micro;
|
||||
}
|
||||
if let Some((map, source)) = input {
|
||||
if !generator.kind.inputs().contains(&map) {
|
||||
return Err(bad(CMD, format!("this generator has no `{}` input", map.id())));
|
||||
match input {
|
||||
Some((GeneratorInput::Map(map), source)) => {
|
||||
if !generator.inputs_in_use().contains(&map) {
|
||||
return Err(bad(CMD, format!("this generator does not read a `{}` input", map.id())));
|
||||
}
|
||||
match source {
|
||||
Some(source) => generator.inputs.insert(map, source),
|
||||
None => generator.inputs.remove(&map),
|
||||
};
|
||||
}
|
||||
|
||||
match source {
|
||||
Some(source) => generator.inputs.insert(map, source),
|
||||
None => generator.inputs.remove(&map),
|
||||
};
|
||||
// The generator parser has validated texture support and migrated the section controls
|
||||
Some((GeneratorInput::Texture, source)) => generator.texture.get_or_insert_default().source = source,
|
||||
// generator_from refused the grunge on kinds without wear controls and moved the generator onto them
|
||||
Some((GeneratorInput::Grunge, source)) => generator.grunge = source,
|
||||
// generator_from refused micro details on kinds without them and created them
|
||||
Some((GeneratorInput::MicroHeight, source)) => {
|
||||
if let Some(micro) = generator.micro.as_mut() {
|
||||
micro.height_source = source;
|
||||
}
|
||||
}
|
||||
Some((GeneratorInput::Image, source)) => {
|
||||
if generator.kind != GeneratorKind::GrayscaleConversion {
|
||||
return Err(bad(CMD, "only Grayscale Conversion reads an `image` input"));
|
||||
}
|
||||
|
||||
let mut grayscale = generator.grayscale_controls().unwrap_or_default();
|
||||
grayscale.source = source;
|
||||
generator.controls = Some(Box::new(KindControls::Grayscale(grayscale)));
|
||||
}
|
||||
Some((GeneratorInput::MicroNormal, source)) => {
|
||||
if let Some(micro) = generator.micro.as_mut() {
|
||||
micro.normal_source = source;
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if let Some(edit) = micro {
|
||||
edit.apply(CMD, generator)?;
|
||||
}
|
||||
}
|
||||
_ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")),
|
||||
@@ -939,6 +1279,41 @@ fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A generator of kind `name` at its defaults to replace generator effect `effect`, or None when it is that kind already
|
||||
fn swapped_generator_kind(s: &Session, effect: LayerId, name: &str) -> Result<Option<Generator>> {
|
||||
const CMD: &str = "effect.set";
|
||||
let kind = GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))?;
|
||||
match &s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?.1.kind {
|
||||
EffectKind::Generator(current) if current.kind == kind => Ok(None),
|
||||
EffectKind::Generator(current) => Ok(Some(swapped_kind(current, kind))),
|
||||
other => Err(bad(CMD, format!("`generator` changes generator effects only, not {}", other.name().to_ascii_lowercase()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `current` as a `kind` generator: the settings every kind shares and the inputs `kind` reads stay, its own controls start from `kind`'s defaults
|
||||
fn swapped_kind(current: &Generator, kind: GeneratorKind) -> Generator {
|
||||
let mut inputs = current.inputs.clone();
|
||||
inputs.retain(|map, _| kind.inputs().contains(map));
|
||||
Generator {
|
||||
level: current.level,
|
||||
softness: current.softness,
|
||||
noise_amount: current.noise_amount,
|
||||
noise_scale: current.noise_scale,
|
||||
seed: current.seed,
|
||||
// The offset belongs to the earlier model, which these kinds lack
|
||||
offset: if kind.has_no_earlier_model() { 0.0 } else { current.offset },
|
||||
direction: current.direction,
|
||||
invert: current.invert,
|
||||
global: current.global,
|
||||
resolution: current.resolution,
|
||||
inputs,
|
||||
grunge: current.grunge.clone().filter(|_| WearParameters::defaults(kind).is_some()),
|
||||
texture: current.texture.clone().filter(|_| SectionParameters::defaults(kind).is_some()),
|
||||
micro: swapped_micro(current.micro.as_deref(), kind),
|
||||
..Generator::new(kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Filter `id` built with `p` and its label, to replace filter effect `effect`
|
||||
fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> {
|
||||
const CMD: &str = "effect.set";
|
||||
|
||||
@@ -70,7 +70,14 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
|
||||
set.tile_resolutions = src_set.tile_resolutions.clone();
|
||||
set.channels = src_set.channels.clone();
|
||||
project.texture_sets.push(set);
|
||||
Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }
|
||||
Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
project,
|
||||
pixels: PixelStore::default(),
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -97,6 +104,7 @@ impl Session {
|
||||
pixels: mini.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
mesh: None,
|
||||
mesh_uvs: None,
|
||||
high_poly: Vec::new(),
|
||||
cage: None,
|
||||
bake_paint: BTreeMap::new(),
|
||||
@@ -129,12 +137,22 @@ impl Session {
|
||||
.first()
|
||||
.and_then(|t| t.stack.last().copied())
|
||||
.ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?;
|
||||
|
||||
let resources: BTreeMap<String, Arc<Vec<u8>>> = project_file.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
|
||||
let source = Document { bake_paint: BTreeMap::new(), project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), resources };
|
||||
let source = Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
project: project_file.project,
|
||||
pixels: project_file.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
resources,
|
||||
};
|
||||
|
||||
let id = self.edit("Add smart material", |s| {
|
||||
for (name, bytes) in &source.resources {
|
||||
s.doc.resources.entry(name.clone()).or_insert_with(|| Arc::clone(bytes));
|
||||
}
|
||||
|
||||
let ts = s.ts();
|
||||
let sel = s.selected_layer();
|
||||
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
|
||||
@@ -144,6 +162,7 @@ impl Session {
|
||||
s.target = StackTarget::Content;
|
||||
Ok(id)
|
||||
})?;
|
||||
|
||||
self.sync_images();
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! The micro details controls `effect.add.generator` and `effect.set` take
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{Generator, GeneratorKind, MicroCurvatureType, MicroDetails, SectionParameters, WearParameters};
|
||||
|
||||
use crate::Result;
|
||||
use crate::commands::{bad, boolp, f32p, strp};
|
||||
|
||||
/// The micro details controls
|
||||
pub const MICRO_KEYS: [&str; 8] =
|
||||
["useMicroDetails", "microHeight", "microNormal", "microCurvatureType", "microCurvatureIntensity", "microHeightIntensity", "microAoRadius", "microAoDepth"];
|
||||
|
||||
/// The input names of the micro height and micro normal images, beside the mesh map ids
|
||||
pub const MICRO_HEIGHT_INPUT: &str = "microHeight";
|
||||
pub const MICRO_NORMAL_INPUT: &str = "microNormal";
|
||||
|
||||
/// Whether micro details control `key` changes a generator of `kind`
|
||||
pub fn micro_key_applies(kind: GeneratorKind, key: &str) -> bool {
|
||||
match key {
|
||||
"useMicroDetails" => MicroDetails::has_switch(kind),
|
||||
"microCurvatureType" | "microCurvatureIntensity" | "microHeightIntensity" => MicroDetails::has_curvature(kind),
|
||||
"microAoRadius" | "microAoDepth" => MicroDetails::has_occlusion(kind),
|
||||
_ => MicroDetails::defaults(kind).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The micro details controls in `params` (a micro height or normal input counts as one): they move a generator off its earlier model onto the reference's controls; `earlier_keys` are the keys that keep it there
|
||||
pub fn micro_from(command: &str, params: &Value, generator: &mut Generator, earlier_keys: &[&str]) -> Result<()> {
|
||||
let input_given = matches!(strp(params, "input"), Some(MICRO_HEIGHT_INPUT | MICRO_NORMAL_INPUT));
|
||||
let mut requested_keys = MICRO_KEYS.iter().filter(|key| params.get(**key).is_some()).peekable();
|
||||
if requested_keys.peek().is_none() && !input_given {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let kind = generator.kind;
|
||||
let Some(defaults) = MicroDetails::defaults(kind) else {
|
||||
return Err(bad(command, format!("{} has no micro details: only Curvature, Ambient Occlusion and the wear kinds have them", kind.label())));
|
||||
};
|
||||
|
||||
if let Some(unused) = requested_keys.find(|key| !micro_key_applies(kind, key)) {
|
||||
return Err(bad(command, format!("{} has no `{unused}`", kind.label())));
|
||||
}
|
||||
|
||||
if WearParameters::defaults(kind).is_some() && ["blur", "balance", "contrast"].iter().any(|key| params.get(*key).is_some()) {
|
||||
return Err(bad(command, format!("{} has no global blur, balance or contrast beside its micro details", kind.label())));
|
||||
}
|
||||
|
||||
if earlier_keys.iter().any(|key| params.get(*key).is_some()) {
|
||||
return Err(bad(command, "level, softness, noise and offset drive the earlier model: give them or the micro details, not both"));
|
||||
}
|
||||
|
||||
// Validate the switches before they can change the generator model
|
||||
for key in ["useMicroDetails", "microHeight", "microNormal"] {
|
||||
if params.get(key).is_some_and(|value| !value.is_boolean()) {
|
||||
return Err(bad(command, format!("`{key}` must be a boolean")));
|
||||
}
|
||||
}
|
||||
|
||||
if generator.on_earlier_model() {
|
||||
generator.offset = 0.0;
|
||||
if let Some(wear) = WearParameters::defaults(kind) {
|
||||
generator.wear = Some(wear);
|
||||
} else {
|
||||
let fresh = Generator::new(kind);
|
||||
(generator.level, generator.softness, generator.noise_amount, generator.noise_scale) =
|
||||
(fresh.level, fresh.softness, fresh.noise_amount, fresh.noise_scale);
|
||||
generator.section = SectionParameters::defaults(kind);
|
||||
}
|
||||
}
|
||||
|
||||
let micro = generator.micro.get_or_insert_with(|| Box::new(defaults));
|
||||
micro.earlier = false;
|
||||
for (key, value) in [("useMicroDetails", &mut micro.enabled), ("microHeight", &mut micro.height), ("microNormal", &mut micro.normal)] {
|
||||
if let Some(given) = boolp(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
|
||||
for (key, value) in [
|
||||
("microCurvatureIntensity", &mut micro.curvature_intensity),
|
||||
("microHeightIntensity", &mut micro.height_intensity),
|
||||
("microAoRadius", &mut micro.ao_radius),
|
||||
("microAoDepth", &mut micro.ao_depth),
|
||||
] {
|
||||
if let Some(given) = f32p(params, key) {
|
||||
*value = given;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(value) = params.get("microCurvatureType") {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`microCurvatureType` must be a string"))?;
|
||||
micro.curvature_type = MicroCurvatureType::parse(name).ok_or_else(|| bad(command, format!("unknown curvature type `{name}`")))?;
|
||||
}
|
||||
|
||||
**micro = micro.as_ref().clone().clamped(kind);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `current`'s micro details carried onto a `kind` generator: its images stay, its controls start from `kind`'s defaults
|
||||
pub fn swapped_micro(current: Option<&MicroDetails>, kind: GeneratorKind) -> Option<Box<MicroDetails>> {
|
||||
let current = current.filter(|micro| micro.sources().next().is_some())?;
|
||||
let defaults = MicroDetails::defaults(kind)?;
|
||||
Some(Box::new(MicroDetails { height_source: current.height_source.clone(), normal_source: current.normal_source.clone(), ..defaults }))
|
||||
}
|
||||
@@ -2,9 +2,14 @@
|
||||
//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId};
|
||||
use texturecraft_compose::ImageRes;
|
||||
use texturecraft_core::{
|
||||
BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural,
|
||||
ProceduralKind, Source,
|
||||
};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
use texturecraft_texel::TILE;
|
||||
@@ -14,7 +19,7 @@ pub use crate::material_preview_pixel::MaterialPreviewPixel;
|
||||
use crate::orb_camera::OrbCamera;
|
||||
use crate::preview::Sample;
|
||||
use crate::session::Document;
|
||||
use crate::{EngineError, Result, Session, materials};
|
||||
use crate::{EngineError, Result, Session, materials, smart_masks};
|
||||
|
||||
/// Bake resolution in texels; 256 loses the thin edge lines
|
||||
const TEXTURE_PX: u32 = 512;
|
||||
@@ -48,6 +53,16 @@ pub struct OrbPreview {
|
||||
cameras: Vec<OrbCamera>,
|
||||
}
|
||||
|
||||
/// `generator` with clouds in Grayscale Conversion's empty image slot: it grays the image it is given, and its picture would be black without one
|
||||
fn with_sample_image(mut generator: Generator) -> Generator {
|
||||
if let Some(KindControls::Grayscale(grayscale)) = generator.controls.as_deref_mut()
|
||||
&& grayscale.source.is_none()
|
||||
{
|
||||
grayscale.source = Some(Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() });
|
||||
}
|
||||
generator
|
||||
}
|
||||
|
||||
impl OrbPreview {
|
||||
/// Bake the orb once (previews of any size reuse it)
|
||||
pub fn new() -> Result<OrbPreview> {
|
||||
@@ -78,9 +93,49 @@ impl OrbPreview {
|
||||
}
|
||||
|
||||
crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?;
|
||||
// Previews need no undo history; retaining snapshots grows memory across presets
|
||||
self.session.undo.clear();
|
||||
|
||||
// Discard preview undo snapshots between presets
|
||||
self.session.undo.clear();
|
||||
self.mask_pixels(size)
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels of a mask holding one generator of `kind` at its defaults, None outside the shape (and for sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`])
|
||||
pub fn generator(&mut self, kind: GeneratorKind, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
self.generator_of(with_sample_image(Generator::new(kind)), size)
|
||||
}
|
||||
|
||||
/// [`Self::generator`] for `generator` as given (a Curvature generator with one detail size alone)
|
||||
pub fn generator_of(&mut self, generator: Generator, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
if !valid_size(size) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Each generator goes on the bare shape, not over the previous mask
|
||||
(self.session.doc, self.session.selected) = self.bare.clone();
|
||||
let effects = vec![(EffectKind::Generator(generator), BlendMode::Normal)];
|
||||
let mask = smart_masks::build_mask(&mut self.session.doc.project, MaskBackground::Black, effects);
|
||||
self.session.doc.project.layer_mut(self.layer).ok()?.mask = Some(mask);
|
||||
self.mask_pixels(size)
|
||||
}
|
||||
|
||||
/// [`Self::generator_of`] with `images` (the images the generator reads, by name) loaded for this render only
|
||||
pub fn generator_reading(&mut self, generator: Generator, images: &[(String, Arc<ImageRes>)], size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
let replaced: Vec<_> = images.iter().map(|(name, image)| (name.clone(), self.session.images.insert(name.clone(), image.clone()))).collect();
|
||||
let pixels = self.generator_of(generator, size);
|
||||
|
||||
// Restore in reverse so a name given twice ends as it began
|
||||
for (name, previous) in replaced.into_iter().rev() {
|
||||
match previous {
|
||||
Some(previous) => self.session.images.insert(name, previous),
|
||||
None => self.session.images.remove(&name),
|
||||
};
|
||||
}
|
||||
|
||||
pixels
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels of the preview layer's current mask, with None outside the shape
|
||||
fn mask_pixels(&mut self, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
let camera = camera_for(&mut self.cameras, &self.session, size)?;
|
||||
let values = self.session.mask_at(self.layer, &camera.texels)?;
|
||||
|
||||
@@ -213,6 +268,24 @@ mod tests {
|
||||
pixels.iter().flatten().map(|pixel| pixel.mask).sum::<f32>() / pixels.iter().flatten().count().max(1) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_render_reading_an_image_twice_leaves_the_orbs_own_images() {
|
||||
let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
let layer = session.doc.project.texture_set(SET).unwrap().stack[0];
|
||||
let bare = (session.doc.clone(), session.selected.clone());
|
||||
let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() };
|
||||
let image = |value| Arc::new(ImageRes::new(1, 1, vec![[value; 4]], false));
|
||||
let own = image(0.1);
|
||||
preview.session.images.insert("shared.png".into(), own.clone());
|
||||
|
||||
let brought = image(0.9);
|
||||
let images = [("shared.png".into(), brought.clone()), ("shared.png".into(), brought.clone()), ("added.png".into(), brought)];
|
||||
preview.generator_reading(Generator::new(GeneratorKind::Dirt), &images, 0);
|
||||
|
||||
assert!(preview.session.images.get("shared.png").is_some_and(|kept| Arc::ptr_eq(kept, &own)), "the orb's own image is back");
|
||||
assert!(!preview.session.images.contains_key("added.png"), "an image it lacked is gone again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_preview_sizes_are_rejected_before_changing_the_shape() {
|
||||
let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
@@ -262,6 +335,41 @@ mod tests {
|
||||
assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_previews_render_on_the_orb_and_each_starts_from_the_bare_shape() {
|
||||
let size = 24;
|
||||
let mut preview = OrbPreview::new().unwrap();
|
||||
for kind in GeneratorKind::ALL {
|
||||
let pixels = preview.generator(kind, size).unwrap_or_else(|| panic!("{kind:?}"));
|
||||
assert_eq!(pixels.len(), size * size, "{kind:?}");
|
||||
assert!(pixels[0].is_none(), "{kind:?}: the corners are outside the shape");
|
||||
for pixel in pixels.iter().flatten() {
|
||||
assert!((0.0..=1.0).contains(&pixel.mask) && pixel.normal.is_finite() && pixel.coverage > 0.0, "{kind:?}: {pixel:?}");
|
||||
}
|
||||
}
|
||||
|
||||
let (edges, dirt) = (preview.generator(GeneratorKind::EdgeWear, size).unwrap(), preview.generator(GeneratorKind::Dirt, size).unwrap());
|
||||
assert!(difference(&edges, &dirt) > 0.05, "edge wear and dirt differ: {}", difference(&edges, &dirt));
|
||||
|
||||
// A smart mask rendered in between leaves nothing behind
|
||||
preview.mask("dirt_cavities", size).unwrap();
|
||||
assert_eq!(preview.generator(GeneratorKind::EdgeWear, size).unwrap(), edges);
|
||||
assert!(preview.generator(GeneratorKind::EdgeWear, 0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_live_grayscale_preview_preserves_an_empty_slot() {
|
||||
let mut preview = OrbPreview::new().unwrap();
|
||||
let generator = Generator::new(GeneratorKind::GrayscaleConversion);
|
||||
let thumbnail = preview.generator(GeneratorKind::GrayscaleConversion, 24).unwrap();
|
||||
let expected = preview.generator_of(generator.clone(), 24).unwrap();
|
||||
|
||||
let live = preview.generator_reading(generator, &[], 24).unwrap();
|
||||
|
||||
assert!(difference(&thumbnail, &expected) > 0.05, "the catalog thumbnail demonstrates the effect on a sample");
|
||||
assert!(live == expected, "the configured generator renders its actual input");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_materials_render_on_the_orb_and_show_their_wear() {
|
||||
let size = 24;
|
||||
|
||||
@@ -5,18 +5,15 @@ use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use texturecraft_compose::MaskGray;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, NO_TRI};
|
||||
use texturecraft_geom::triangle_partition::CORNER_GRID_STEPS;
|
||||
use texturecraft_geom::{Mesh, NO_TRI, TrianglePartition};
|
||||
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
|
||||
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::polygon_fill_drag::PolygonFillDrag;
|
||||
use crate::session::Session;
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner
|
||||
const CORNER_GRID_STEPS: f32 = 1e5;
|
||||
|
||||
impl Session {
|
||||
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
|
||||
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
@@ -178,7 +175,7 @@ impl Session {
|
||||
match self.tool.fill_mode {
|
||||
FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::<u32>::new()),
|
||||
FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges),
|
||||
FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges),
|
||||
FillMode::UvIsland => TrianglePartition::uv_islands(&self.mesh, material),
|
||||
FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges),
|
||||
}
|
||||
}
|
||||
@@ -298,12 +295,6 @@ fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range<usize> {
|
||||
first..end.max(first)
|
||||
}
|
||||
|
||||
/// Texture coordinates of `triangle`'s corners
|
||||
fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> {
|
||||
let [first, second, third] = mesh.tri(triangle)?;
|
||||
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
|
||||
}
|
||||
|
||||
/// The polygon diagonals of `triangle`: edges the importer added to split a polygon
|
||||
fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> {
|
||||
let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0);
|
||||
@@ -318,14 +309,6 @@ fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart
|
||||
fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> {
|
||||
let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64);
|
||||
let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() };
|
||||
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
|
||||
/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected
|
||||
fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> {
|
||||
let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64));
|
||||
|
||||
@@ -9,7 +9,7 @@ use texturecraft_paint::EyeDepth;
|
||||
use texturecraft_texel::TileImage;
|
||||
|
||||
use crate::session::{Document, StackTarget};
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
use texturecraft_geom::TrianglePartition;
|
||||
|
||||
/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends
|
||||
pub(crate) struct PolygonFillDrag {
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::collections::{BTreeSet, HashSet};
|
||||
use texturecraft_geom::glam::Mat3;
|
||||
|
||||
use crate::session::Session;
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
use texturecraft_geom::TrianglePartition;
|
||||
|
||||
/// How far a mirrored face centre may be from the surface and still count as on it, as a fraction of the mesh's bounding-box diagonal
|
||||
const MIRROR_TOLERANCE: f32 = 1e-3;
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
//! dialog's Output templates tab list, read, save and remove. On the desktop the user presets
|
||||
//! are mirrored as `<name>.json` files in a library folder (see [`Session::load_export_presets`]).
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem};
|
||||
use texturecraft_formats::{ExportPreset, builtin_preset, builtin_presets, preset_from_json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, strp};
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Most user presets kept (and read from the library folder).
|
||||
@@ -65,16 +67,18 @@ impl UserPresets {
|
||||
|| self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name)))
|
||||
}
|
||||
|
||||
/// `name`, or `name 2`, `name 3`… (shortened to fit) when taken.
|
||||
fn unique_name(&self, name: &str, skip: Option<usize>) -> String {
|
||||
/// The first available name, adding a numbered suffix and shortening the base to fit.
|
||||
fn unique_name(&self, name: &str, skip: Option<usize>) -> Option<String> {
|
||||
// File keys also cover case-insensitive name matches
|
||||
let file_keys: HashSet<_> = self.list.iter().enumerate().filter(|(index, _)| Some(*index) != skip).map(|(_, preset)| file_key(&preset.name)).collect();
|
||||
|
||||
(1..=MAX_USER_PRESETS + 1)
|
||||
.map(|k| {
|
||||
let suffix = if k == 1 { String::new() } else { format!(" {k}") };
|
||||
.map(|number| {
|
||||
let suffix = if number == 1 { String::new() } else { format!(" {number}") };
|
||||
let base: String = name.chars().take(MAX_PRESET_NAME.saturating_sub(suffix.len())).collect();
|
||||
format!("{}{suffix}", base.trim_end())
|
||||
})
|
||||
.find(|n| !self.taken(n, skip))
|
||||
.unwrap_or_else(|| name.to_string())
|
||||
.find(|candidate| !file_keys.contains(&file_key(candidate)) && builtin_preset(candidate).is_none())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -163,32 +167,50 @@ pub fn preset_param(v: &Value, cmd: &str) -> Result<ExportPreset> {
|
||||
Ok(preset)
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn save(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "export.preset.save";
|
||||
let mut preset = preset_param(p.get("preset").ok_or_else(|| bad(CMD, "`preset` is required"))?, CMD)?;
|
||||
let lib = &mut s.export_presets;
|
||||
let renamed = match strp(p, "rename") {
|
||||
Some(old) => Some(lib.find(old).ok_or_else(|| bad(CMD, format!("no user export preset `{old}` to rename")))?),
|
||||
None => None,
|
||||
let preset_value = params.get("preset").ok_or_else(|| bad(CMD, "`preset` is required"))?;
|
||||
let rename_from = match params.get("rename") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(name)) => Some(name),
|
||||
Some(_) => return Err(bad(CMD, "`rename` must be a preset name")),
|
||||
};
|
||||
let target = renamed.or_else(|| lib.find(&preset.name));
|
||||
if boolp(p, "unique") == Some(true) {
|
||||
preset.name = lib.unique_name(&preset.name, renamed);
|
||||
} else if lib.taken(&preset.name, target) {
|
||||
let unique = match params.get("unique") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(Value::Bool(unique)) => *unique,
|
||||
Some(_) => return Err(bad(CMD, "`unique` must be a boolean")),
|
||||
};
|
||||
|
||||
let mut preset = preset_param(preset_value, CMD)?;
|
||||
let library = &mut session.export_presets;
|
||||
let target_index = match rename_from {
|
||||
Some(old_name) => Some(library.find(old_name).ok_or_else(|| bad(CMD, format!("no user export preset `{old_name}` to rename")))?),
|
||||
None if unique => None,
|
||||
None => library.find(&preset.name),
|
||||
};
|
||||
|
||||
if !unique && library.taken(&preset.name, target_index) {
|
||||
return Err(bad(CMD, format!("an export preset named \"{}\" exists already (built-in presets are read-only)", preset.name)));
|
||||
}
|
||||
let target = renamed.or_else(|| lib.find(&preset.name));
|
||||
if target.is_none() && lib.list.len() >= MAX_USER_PRESETS {
|
||||
|
||||
if target_index.is_none() && library.list.len() >= MAX_USER_PRESETS {
|
||||
return Err(bad(CMD, format!("at most {MAX_USER_PRESETS} user export presets")));
|
||||
}
|
||||
let previous = target.and_then(|i| lib.list.get(i)).map(|old| old.name.clone());
|
||||
lib.write(&preset, previous.as_deref()).map_err(|e| bad(CMD, e))?;
|
||||
let name = preset.name.clone();
|
||||
match target.and_then(|i| lib.list.get_mut(i)) {
|
||||
Some(slot) => *slot = preset,
|
||||
None => lib.list.push(preset),
|
||||
|
||||
if unique {
|
||||
preset.name = library.unique_name(&preset.name, target_index).ok_or_else(|| bad(CMD, "no unique export preset name is available"))?;
|
||||
}
|
||||
Ok(json!({ "name": name }))
|
||||
|
||||
let previous_name = target_index.and_then(|index| library.list.get(index)).map(|previous| previous.name.as_str());
|
||||
library.write(&preset, previous_name).map_err(|error| bad(CMD, error))?;
|
||||
|
||||
let response = json!({ "name": preset.name });
|
||||
match target_index.and_then(|index| library.list.get_mut(index)) {
|
||||
Some(slot) => *slot = preset,
|
||||
None => library.list.push(preset),
|
||||
}
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -226,40 +248,113 @@ mod tests {
|
||||
assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset(" Mine ")})).unwrap()["name"], "Mine");
|
||||
let got = run(&mut s, "export.preset.get", json!({"name": "mine"})).unwrap();
|
||||
assert_eq!(got, preset("Mine"), "round trip through the command");
|
||||
// Saving the same name replaces; a clash with a built-in or with `unique` renames.
|
||||
|
||||
// A same-name save replaces the current preset
|
||||
let mut edited = preset("Mine");
|
||||
edited["maps"][0]["bit_depth"] = json!(16);
|
||||
run(&mut s, "export.preset.save", json!({"preset": edited})).unwrap();
|
||||
assert_eq!(s.export_presets.list.len(), 1);
|
||||
assert_eq!(s.export_preset("Mine").unwrap().maps[0].bit_depth, 16);
|
||||
|
||||
// Built-ins need a unique name for a user copy
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("Separate maps")})).is_err());
|
||||
assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset("Separate maps"), "unique": true})).unwrap()["name"], "Separate maps 2");
|
||||
assert_eq!(run(&mut s, "export.preset.save", json!({"preset": preset("mine"), "unique": true})).unwrap()["name"], "mine 2");
|
||||
// Renaming onto another preset fails; onto a free name keeps the position.
|
||||
|
||||
// Renaming to a free name keeps the library position
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("Mine"), "rename": "mine 2"})).is_err());
|
||||
run(&mut s, "export.preset.save", json!({"preset": preset("Renamed"), "rename": "Mine"})).unwrap();
|
||||
let names: Vec<&str> = s.export_presets.list.iter().map(|p| p.name.as_str()).collect();
|
||||
assert_eq!(names, ["Renamed", "Separate maps 2", "mine 2"]);
|
||||
|
||||
let listed = run(&mut s, "export.presets", json!({})).unwrap();
|
||||
assert!(listed.as_array().unwrap().iter().any(|p| p["name"] == "Renamed" && p["builtin"] == false));
|
||||
assert!(run(&mut s, "export.preset.remove", json!({"name": "Separate maps"})).is_err(), "built-ins are read-only");
|
||||
run(&mut s, "export.preset.remove", json!({"name": "renamed"})).unwrap();
|
||||
assert!(run(&mut s, "export.preset.get", json!({"name": "Renamed"})).is_err());
|
||||
// Presets survive opening another project.
|
||||
|
||||
// Presets survive opening another project
|
||||
run(&mut s, "project.new", json!({"resolution": 128})).unwrap();
|
||||
assert_eq!(s.export_presets.list.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_save_options_do_not_replace_a_user_preset() {
|
||||
let mut session = session();
|
||||
let original = preset("Mine");
|
||||
run(&mut session, "export.preset.save", json!({"preset": original})).unwrap();
|
||||
let mut replacement = original.clone();
|
||||
replacement["maps"][0]["bit_depth"] = json!(16);
|
||||
|
||||
for (key, invalid) in [("unique", json!("true")), ("rename", json!(7))] {
|
||||
let mut params = json!({"preset": replacement});
|
||||
params[key] = invalid;
|
||||
|
||||
let error = run(&mut session, "export.preset.save", params).unwrap_err();
|
||||
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Mine"})).unwrap(), original);
|
||||
assert!(error.to_string().contains(&format!("`{key}`")), "{error}");
|
||||
}
|
||||
|
||||
run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": null, "rename": null})).unwrap();
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Mine"})).unwrap(), replacement);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unique_saves_skip_presets_with_colliding_file_stems() {
|
||||
let mut session = Session::closed().unwrap();
|
||||
for name in ["My Preset", "My_Preset_2"] {
|
||||
run(&mut session, "export.preset.save", json!({"preset": preset(name)})).unwrap();
|
||||
}
|
||||
|
||||
let saved = run(&mut session, "export.preset.save", json!({"preset": preset("My Preset"), "unique": true})).unwrap();
|
||||
|
||||
assert_eq!(saved["name"], "My Preset 3");
|
||||
for name in ["My Preset", "My_Preset_2", "My Preset 3"] {
|
||||
assert_eq!(session.export_preset(name).unwrap().name, name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unique_save_at_capacity_requires_an_explicit_rename() {
|
||||
let mut session = Session::closed().unwrap();
|
||||
|
||||
// At the name length limit, adding the first suffix can reproduce the requested name
|
||||
for number in 2..=MAX_USER_PRESETS + 1 {
|
||||
let suffix = format!(" {number}");
|
||||
let name = format!("{}{suffix}", "x".repeat(MAX_PRESET_NAME - suffix.len()));
|
||||
run(&mut session, "export.preset.save", json!({"preset": preset(&name)})).unwrap();
|
||||
}
|
||||
|
||||
let first_name = session.export_presets.list[0].name.clone();
|
||||
let original = run(&mut session, "export.preset.get", json!({"name": first_name})).unwrap();
|
||||
let mut replacement = original.clone();
|
||||
replacement["maps"][0]["bit_depth"] = json!(16);
|
||||
|
||||
let result = run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": true}));
|
||||
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": first_name})).unwrap(), original);
|
||||
assert!(result.is_err());
|
||||
|
||||
replacement["name"] = json!("Renamed");
|
||||
run(&mut session, "export.preset.save", json!({"preset": replacement, "unique": true, "rename": first_name})).unwrap();
|
||||
|
||||
assert_eq!(run(&mut session, "export.preset.get", json!({"name": "Renamed"})).unwrap(), replacement);
|
||||
assert!(run(&mut session, "export.preset.get", json!({"name": first_name})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_presets_are_refused() {
|
||||
let mut s = session();
|
||||
let mut evil = preset("Evil");
|
||||
evil["maps"][0]["file"] = json!("../../$mesh");
|
||||
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": evil})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": "nope"})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("")})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset(&"x".repeat(200))})).is_err());
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("a"), "rename": "missing"})).is_err());
|
||||
|
||||
assert!(s.export_presets.list.is_empty());
|
||||
}
|
||||
|
||||
@@ -291,7 +386,7 @@ mod tests {
|
||||
let set = s.doc.project.texture_sets[0].name.clone();
|
||||
let dir = std::env::temp_dir().join(format!("tc_user_preset_export_{}", std::process::id()));
|
||||
|
||||
// By name and as an inline object: the same files
|
||||
// Named and inline presets produce the same files
|
||||
for preset in [json!("packed"), packed] {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let r = run(&mut s, "file.exportTextures", json!({"dir": dir.display().to_string(), "preset": preset, "ts": 0})).unwrap();
|
||||
@@ -325,10 +420,12 @@ mod tests {
|
||||
assert_eq!(s.load_export_presets(dir.clone()).len(), 1, "the broken file is reported");
|
||||
run(&mut s, "export.preset.save", json!({"preset": preset("My Preset")})).unwrap();
|
||||
assert!(dir.join("My_Preset.json").is_file());
|
||||
// Names sharing a file stem clash instead of overwriting each other's file.
|
||||
|
||||
// Reject aliases that would overwrite the same library file
|
||||
assert!(run(&mut s, "export.preset.save", json!({"preset": preset("My_Preset")})).is_err());
|
||||
run(&mut s, "export.preset.save", json!({"preset": preset("Other"), "rename": "My Preset"})).unwrap();
|
||||
assert!(!dir.join("My_Preset.json").exists() && dir.join("Other.json").is_file());
|
||||
|
||||
let mut fresh = session();
|
||||
assert_eq!(fresh.load_export_presets(dir.clone()).len(), 1);
|
||||
assert_eq!(fresh.export_preset("other").unwrap().name, "Other");
|
||||
|
||||
@@ -31,6 +31,8 @@ pub struct Document {
|
||||
pub bake_paint: BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc<texturecraft_bake::BakePaintMap>>,
|
||||
/// Imported image resources by name: original file bytes.
|
||||
pub resources: BTreeMap<String, Arc<Vec<u8>>>,
|
||||
/// High-definition meshes and cage for baking (saved inside the project)
|
||||
pub bake_meshes: crate::BakeMeshes,
|
||||
}
|
||||
|
||||
/// Derived per-texture-set data (rebuilt when the mesh or resolution changes).
|
||||
@@ -426,8 +428,6 @@ pub struct Session {
|
||||
pub bvh: Arc<Bvh>,
|
||||
/// Original mesh file (saved inside the project); None for built-in meshes.
|
||||
pub mesh_source: Option<(String, Vec<u8>)>,
|
||||
/// High-definition meshes and cage for baking (saved inside the project).
|
||||
pub bake_meshes: crate::BakeMeshes,
|
||||
pub caches: Vec<SetCache>,
|
||||
pub(crate) undo: Vec<(String, Document)>,
|
||||
pub(crate) redo: Vec<(String, Document)>,
|
||||
@@ -525,7 +525,6 @@ impl Session {
|
||||
mesh,
|
||||
bvh: Arc::new(bvh),
|
||||
mesh_source,
|
||||
bake_meshes: Default::default(),
|
||||
caches,
|
||||
undo: Vec::new(),
|
||||
redo: Vec::new(),
|
||||
@@ -604,8 +603,7 @@ impl Session {
|
||||
Session::new_project_tiled(name, mesh, mesh_ref, mesh_source, resolution, None)
|
||||
}
|
||||
|
||||
/// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` for every
|
||||
/// set, `Some(false)` for none, `None` for the sets whose UVs leave tile 1001.
|
||||
/// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` every set, `Some(false)` none, `None` the sets whose UVs leave tile 1001
|
||||
pub fn new_project_tiled(
|
||||
name: &str,
|
||||
mesh: Mesh,
|
||||
@@ -628,11 +626,20 @@ impl Session {
|
||||
ts.stack.push(id);
|
||||
project.texture_sets.push(ts);
|
||||
}
|
||||
|
||||
let mut s = Session::new(
|
||||
Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() },
|
||||
Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
project,
|
||||
pixels: PixelStore::default(),
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
},
|
||||
mesh,
|
||||
mesh_source,
|
||||
)?;
|
||||
|
||||
s.log.append(log);
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
@@ -79,14 +79,25 @@ pub fn find(name: &str) -> Option<&'static SmartMask> {
|
||||
|
||||
const UP: [f32; 3] = [0.0, 1.0, 0.0];
|
||||
|
||||
/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes).
|
||||
/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes or the wear, section and light controls)
|
||||
pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind {
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) })
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, wear: None, section: None, light: None, ..Generator::new(kind) })
|
||||
}
|
||||
|
||||
/// A direction or position generator (`invert` flips the result).
|
||||
pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind {
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) })
|
||||
EffectKind::Generator(Generator {
|
||||
level,
|
||||
softness,
|
||||
noise_amount: noise,
|
||||
direction,
|
||||
invert,
|
||||
detail: None,
|
||||
wear: None,
|
||||
section: None,
|
||||
light: None,
|
||||
..Generator::new(kind)
|
||||
})
|
||||
}
|
||||
|
||||
/// A triplanar grayscale pattern fill
|
||||
@@ -223,14 +234,17 @@ impl Session {
|
||||
.and_then(|root| pf.project.layers.get(&root))
|
||||
.and_then(|l| l.mask.clone())
|
||||
.ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?;
|
||||
|
||||
let resources: BTreeMap<String, Arc<Vec<u8>>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
|
||||
let src = crate::session::Document {
|
||||
bake_meshes: Default::default(),
|
||||
bake_paint: BTreeMap::new(),
|
||||
project: pf.project,
|
||||
pixels: pf.pixels,
|
||||
baked: BTreeMap::new(),
|
||||
resources: BTreeMap::new(),
|
||||
};
|
||||
|
||||
let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default();
|
||||
self.edit(&format!("Apply smart mask {label}"), |s| {
|
||||
let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! with the brush as its alpha or to place as a decal.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_formats::sanitize_resource_name;
|
||||
use texturecraft_paint::text::render_text;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, color_param, f32p, strp};
|
||||
@@ -94,16 +95,57 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow:
|
||||
}
|
||||
}
|
||||
|
||||
fn add_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "resource.text";
|
||||
let text = strp(p, "text").ok_or_else(|| bad(cmd, "`text` is required"))?;
|
||||
let (font, index) = font_bytes(strp(p, "font"), strp(p, "style"))?;
|
||||
let size = f32p(p, "size").unwrap_or(256.0).clamp(8.0, 1024.0);
|
||||
let img = render_text(&font, index, text, size).map_err(|e| bad(cmd, e))?;
|
||||
let rgb = color_param(cmd, p, "color")?.unwrap_or([1.0; 3]).map(|c| (texturecraft_texel::linear_to_srgb(c.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
let png = texturecraft_formats::coverage_png(img.width, img.height, &img.coverage, rgb).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
// The resource is named after the text (its first line, shortened) unless a name is given.
|
||||
let label: String = strp(p, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(32).collect();
|
||||
let name = s.import_resource_bytes(&format!("Text {}.png", label.trim()), png)?;
|
||||
Ok(json!({ "name": name, "width": img.width, "height": img.height }))
|
||||
fn add_text(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const DEFAULT_TEXELS_PER_EM: f32 = 256.0;
|
||||
const MIN_TEXELS_PER_EM: f32 = 8.0;
|
||||
const MAX_TEXELS_PER_EM: f32 = 1024.0;
|
||||
const MAX_LABEL_CHARS: usize = 32;
|
||||
|
||||
let command = "resource.text";
|
||||
let text = strp(params, "text").ok_or_else(|| bad(command, "`text` is required"))?;
|
||||
let (font, face_index) = font_bytes(strp(params, "font"), strp(params, "style"))?;
|
||||
let texels_per_em = f32p(params, "size").unwrap_or(DEFAULT_TEXELS_PER_EM).clamp(MIN_TEXELS_PER_EM, MAX_TEXELS_PER_EM);
|
||||
|
||||
let image = render_text(&font, face_index, text, texels_per_em).map_err(|error| bad(command, error))?;
|
||||
drop(font);
|
||||
|
||||
let srgb_bytes = color_param(command, params, "color")?
|
||||
.unwrap_or([1.0; 3])
|
||||
.map(|channel| (texturecraft_texel::linear_to_srgb(channel.clamp(0.0, 1.0)) * 255.0).round() as u8);
|
||||
let (width, height) = (image.width, image.height);
|
||||
let png_bytes = texturecraft_formats::coverage_png(width, height, &image.coverage, srgb_bytes).map_err(|error| bad(command, error.to_string()))?;
|
||||
drop(image);
|
||||
|
||||
let label: String = strp(params, "name").unwrap_or_else(|| text.lines().next().unwrap_or_default()).chars().take(MAX_LABEL_CHARS).collect();
|
||||
|
||||
// Treat the label as text before the importer extracts a basename
|
||||
let file_name = sanitize_resource_name(&format!("Text {}.png", label.trim()));
|
||||
|
||||
let name = session.import_resource_bytes(&file_name, png_bytes)?;
|
||||
|
||||
Ok(json!({ "name": name, "width": width, "height": height }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn text_resource_name_keeps_the_label_across_a_slash() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
|
||||
let resource = crate::execute(&mut session, "resource.text", &json!({"text": "1/2", "font": "Hack", "size": 16})).unwrap();
|
||||
|
||||
assert_eq!(resource["name"], "Text_1_2.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_resource_name_keeps_the_explicit_label_across_separators() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
|
||||
let resource =
|
||||
crate::execute(&mut session, "resource.text", &json!({"text": "Plan", "name": "plan\\detail/page", "font": "Hack", "size": 16})).unwrap();
|
||||
|
||||
assert_eq!(resource["name"], "Text_plan_detail_page.png");
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
/// A material's triangles split into groups joined across shared edges
|
||||
pub struct TrianglePartition {
|
||||
/// The triangles of each group
|
||||
pub groups: Vec<Vec<u32>>,
|
||||
/// The index of each triangle's group
|
||||
group_of: HashMap<u32, usize>,
|
||||
}
|
||||
|
||||
impl TrianglePartition {
|
||||
/// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both
|
||||
pub fn new<K: Eq + Hash + Clone>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
|
||||
// Each triangle's edges once, in mesh order so the groups come out the same every time
|
||||
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
|
||||
let position_of: HashMap<u32, usize> = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect();
|
||||
let mut edge_lists: Vec<Vec<K>> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect();
|
||||
let mut by_edge: HashMap<K, Vec<u32>> = HashMap::new();
|
||||
for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) {
|
||||
for edge in triangle_edges {
|
||||
by_edge.entry(edge.clone()).or_default().push(*triangle);
|
||||
}
|
||||
}
|
||||
|
||||
let mut groups = Vec::new();
|
||||
let mut group_of = HashMap::with_capacity(triangles.len());
|
||||
for &start in &triangles {
|
||||
if group_of.contains_key(&start) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut members = Vec::new();
|
||||
let mut stack = vec![start];
|
||||
group_of.insert(start, groups.len());
|
||||
while let Some(triangle) = stack.pop() {
|
||||
members.push(triangle);
|
||||
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
|
||||
// Visit a shared edge once, including when many collapsed faces share the same key
|
||||
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
|
||||
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
|
||||
entry.insert(groups.len());
|
||||
stack.push(neighbour);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups.push(members);
|
||||
}
|
||||
TrianglePartition { groups, group_of }
|
||||
}
|
||||
|
||||
/// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material)
|
||||
pub fn index_of(&self, triangle: u32) -> Option<usize> {
|
||||
self.group_of.get(&triangle).copied()
|
||||
}
|
||||
|
||||
/// The group holding `triangle` (None for a triangle of another material)
|
||||
pub fn group(&self, triangle: u32) -> Option<&[u32]> {
|
||||
self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn triangles_sharing_a_key_join_one_group() {
|
||||
let mesh = primitives::plane(2.0, 2);
|
||||
let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
|
||||
let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]);
|
||||
|
||||
assert_eq!(singles.groups.len(), mesh.triangle_count());
|
||||
assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2);
|
||||
assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2));
|
||||
assert_eq!(pairs.group(99), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_edges_keep_transitive_neighbors() {
|
||||
let mesh = primitives::plane(2.0, 4);
|
||||
let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]);
|
||||
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_shared_edges() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
for subdivisions in [32, 64] {
|
||||
let mesh = primitives::plane(2.0, subdivisions);
|
||||
for collapsed in [false, true] {
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let start = Instant::now();
|
||||
let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| {
|
||||
if collapsed {
|
||||
vec![(0, 0); 3]
|
||||
} else {
|
||||
let [first, second, third] = mesh.tri(triangle).unwrap();
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
});
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
black_box(groups);
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,8 @@
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::project::ENVIRONMENTS;
|
||||
use texturecraft_core::{BakedMap, Channel, EffectKind, EnvAlignment, Filter, Project, ShadowMode, ToneMapping};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p, vec3};
|
||||
use crate::frame_target::FrameTarget;
|
||||
use crate::session::ViewMode;
|
||||
use crate::{Result, Session, cmd};
|
||||
@@ -52,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set camera",
|
||||
[],
|
||||
None,
|
||||
"{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z], ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}",
|
||||
"{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z] (three finite numbers, null keeps the current target), ortho?, rotation?: constrained|free (a free camera also rolls and turns over)}",
|
||||
always,
|
||||
camera_set
|
||||
),
|
||||
@@ -233,37 +232,49 @@ pub(crate) fn camera_json(s: &Session) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
fn camera_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let c = &mut s.camera;
|
||||
match strp(p, "rotation") {
|
||||
Some("free") => c.set_free(true),
|
||||
Some("constrained") => c.set_free(false),
|
||||
Some(o) => return Err(bad("camera.set", format!("unknown rotation `{o}`: constrained or free"))),
|
||||
fn camera_set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const MAX_PITCH_DEGREES: f32 = 89.0;
|
||||
const MIN_DISTANCE_RADII: f32 = 0.05;
|
||||
const MAX_DISTANCE_RADII: f32 = 200.0;
|
||||
const MIN_FOV_DEGREES: f32 = 5.0;
|
||||
const MAX_FOV_DEGREES: f32 = 150.0;
|
||||
|
||||
let target = vec3(params, "target");
|
||||
if target.is_none() && params.get("target").is_some_and(|value| !value.is_null()) {
|
||||
return Err(bad("camera.set", "`target` must be an array of three finite numbers"));
|
||||
}
|
||||
|
||||
let camera = &mut session.camera;
|
||||
match strp(params, "rotation") {
|
||||
Some("free") => camera.set_free(true),
|
||||
Some("constrained") => camera.set_free(false),
|
||||
Some(other) => return Err(bad("camera.set", format!("unknown rotation `{other}`: constrained or free"))),
|
||||
None => {}
|
||||
}
|
||||
if f32p(p, "yaw").is_some() || f32p(p, "pitch").is_some() {
|
||||
// A free camera is put level at the angles
|
||||
let yaw = f32p(p, "yaw").map_or(c.yaw, f32::to_radians);
|
||||
let pitch = f32p(p, "pitch").map_or(c.pitch, |v| v.clamp(-89.0, 89.0).to_radians());
|
||||
c.set_angles(yaw, pitch);
|
||||
|
||||
let yaw_degrees = f32p(params, "yaw");
|
||||
let pitch_degrees = f32p(params, "pitch");
|
||||
if yaw_degrees.is_some() || pitch_degrees.is_some() {
|
||||
// Setting either angle levels a free camera
|
||||
let yaw = yaw_degrees.map_or(camera.yaw, f32::to_radians);
|
||||
let pitch = pitch_degrees.map_or(camera.pitch, |degrees| degrees.clamp(-MAX_PITCH_DEGREES, MAX_PITCH_DEGREES).to_radians());
|
||||
camera.set_angles(yaw, pitch);
|
||||
}
|
||||
if let Some(v) = f32p(p, "distance") {
|
||||
c.distance = v.clamp(c.scene_radius * 0.05, c.scene_radius * 200.0);
|
||||
if let Some(distance) = f32p(params, "distance") {
|
||||
camera.distance = distance.clamp(camera.scene_radius * MIN_DISTANCE_RADII, camera.scene_radius * MAX_DISTANCE_RADII);
|
||||
}
|
||||
if let Some(v) = f32p(p, "fov") {
|
||||
c.fov = v.clamp(5.0, 150.0);
|
||||
if let Some(fov_degrees) = f32p(params, "fov") {
|
||||
camera.fov = fov_degrees.clamp(MIN_FOV_DEGREES, MAX_FOV_DEGREES);
|
||||
}
|
||||
if let Some(t) = p.get("target").and_then(Value::as_array) {
|
||||
let v: Vec<f32> = t.iter().filter_map(Value::as_f64).map(|x| x as f32).collect();
|
||||
if v.len() == 3 && v.iter().all(|x| x.is_finite()) {
|
||||
c.target = Vec3::new(v[0], v[1], v[2]);
|
||||
}
|
||||
if let Some(target) = target {
|
||||
camera.target = target;
|
||||
}
|
||||
if let Some(o) = boolp(p, "ortho") {
|
||||
c.ortho = o;
|
||||
if let Some(ortho) = boolp(params, "ortho") {
|
||||
camera.ortho = ortho;
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(camera_json(s))
|
||||
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(camera_json(session))
|
||||
}
|
||||
|
||||
fn orbit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -403,6 +414,40 @@ mod tests {
|
||||
Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_set_rejects_an_invalid_target_without_changing_the_camera() {
|
||||
let mut session = sphere_session();
|
||||
execute(&mut session, "camera.set", &json!({"target": [1.0, 2.0, 3.0], "fov": 40.0})).unwrap();
|
||||
let before = session.camera;
|
||||
let revision = session.revision;
|
||||
|
||||
for target in [json!([10, "typo", 20, 30]), json!([1, 2]), json!([1, "typo", 3]), json!([1, 2, 1e300]), json!({"x": 1})] {
|
||||
let params = json!({"target": target, "yaw": 35.0, "fov": 90.0, "rotation": "free"});
|
||||
|
||||
let result = execute(&mut session, "camera.set", ¶ms);
|
||||
|
||||
assert!(matches!(result, Err(crate::EngineError::BadParams { cmd, .. }) if cmd == "camera.set"), "{params}");
|
||||
assert_eq!(session.camera, before);
|
||||
assert_eq!(session.revision, revision);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_set_keeps_the_target_when_it_is_omitted_or_null() {
|
||||
let mut session = sphere_session();
|
||||
let target = json!([1.0, 2.0, 3.0]);
|
||||
|
||||
let initial = execute(&mut session, "camera.set", &json!({"target": target, "fov": 40.0})).unwrap();
|
||||
let omitted = execute(&mut session, "camera.set", &json!({"fov": 60.0})).unwrap();
|
||||
let explicit_null = execute(&mut session, "camera.set", &json!({"target": null, "fov": 80.0})).unwrap();
|
||||
|
||||
assert_eq!(initial["target"], target);
|
||||
assert_eq!(omitted["target"], target);
|
||||
assert_eq!(explicit_null["target"], target);
|
||||
assert_ne!(omitted["fov"], initial["fov"]);
|
||||
assert_ne!(explicit_null["fov"], omitted["fov"]);
|
||||
}
|
||||
|
||||
fn pressed(s: &mut Session, command: &str) -> ViewMode {
|
||||
execute(s, command, &json!({})).unwrap();
|
||||
s.view
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Warp projections: the frame a new warp starts from, and Reset frame, which puts a warp's frame and corners back there
|
||||
|
||||
use serde_json::Value;
|
||||
use texturecraft_core::{Decal, Projection};
|
||||
use texturecraft_core::{Decal, Projection, Projector};
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_layer};
|
||||
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset frame",
|
||||
[],
|
||||
None,
|
||||
"{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)",
|
||||
"{layer? | effect?: content or mask fill effect id, keepCorners?: bool} — refit the warp's frame around the mesh. With `keepCorners: true`, also reset the projector's rotation and scale and keep the corners; otherwise reset the corners. Projection Depth, crop, and culling stay",
|
||||
has_layer,
|
||||
reset_frame
|
||||
)]
|
||||
@@ -44,26 +44,39 @@ pub(crate) fn fitted_frame(mesh: &Mesh) -> Decal {
|
||||
/// A fitted frame's smallest side, relative to the mesh diagonal (a flat mesh still gets a frame)
|
||||
const SMALLEST_SIDE: f32 = 1e-3;
|
||||
|
||||
fn reset_frame(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let target = fill_target(s, p, RESET_FRAME)?;
|
||||
let fitted = fitted_frame(&s.mesh);
|
||||
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
|
||||
fn reset_frame(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let target = fill_target(session, params, RESET_FRAME)?;
|
||||
let keep_corners = match params.get("keepCorners") {
|
||||
Some(value) => value.as_bool().ok_or_else(|| bad(RESET_FRAME, "`keepCorners` must be a boolean"))?,
|
||||
None => false,
|
||||
};
|
||||
let fitted = fitted_frame(&session.mesh);
|
||||
let (projection, _) = placement_mut(session, target)?;
|
||||
let mut reset = projection.clone();
|
||||
let Projection::Warp { frame, corners, projector, .. } = &mut reset else {
|
||||
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
|
||||
};
|
||||
|
||||
// A frame already fitted with unpulled corners adds no undo step
|
||||
if *frame == fitted && *corners == Projection::FRAME_CORNERS {
|
||||
*frame = fitted;
|
||||
if keep_corners {
|
||||
// Older warps may still carry a transform separate from the frame
|
||||
let defaults = Projector::default();
|
||||
projector.rotation = defaults.rotation;
|
||||
projector.scale = defaults.scale;
|
||||
} else {
|
||||
*corners = Projection::FRAME_CORNERS;
|
||||
}
|
||||
|
||||
// An unchanged projection adds no undo step
|
||||
if reset == *projection {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
|
||||
s.edit("Reset frame", |s| {
|
||||
let (Projection::Warp { frame, corners, .. }, _) = placement_mut(s, target)? else {
|
||||
return Err(bad(RESET_FRAME, "the fill's projection is not a warp projection"));
|
||||
};
|
||||
|
||||
*frame = fitted;
|
||||
*corners = Projection::FRAME_CORNERS;
|
||||
let label = if keep_corners { "Reset warp transform" } else { "Reset frame" };
|
||||
session.edit(label, |session| {
|
||||
*placement_mut(session, target)?.0 = reset;
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
Reference in new issue
Block a user