mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-30 01:54:29 +01:00
GPU path tracing, depth of field, cameras, glass, filters and decals
- Rendering mode traces on the GPU (compute shaders, ~25x the CPU tracer) with CPU fallback; CLI/MCP render --samples uses the GPU unless --cpu - Depth of field in the viewport and the path tracer; multiple cameras with glTF import; transmission/IOR, coat normal and screen-space subsurface blur; exact 8-bit normal decode - Filter library (18 filters incl. warp, color balance, gradient map, posterize, MatFinish) with a Filters shelf tab; geometry decals; clone from the current layer; anchors inside a content stack; instances across texture-set resolutions; drag saved smart materials Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
85184586da
commit
81d3f5c14c
60 files changed
+6131
-566
No files matched your search
@@ -142,7 +142,8 @@
|
||||
rotation, blur, ACES or linear tone mapping, key-light shadows, bloom, vignette, sharpen and
|
||||
grain, parallax occlusion, and temporal anti-aliasing that refines the image while you look.
|
||||
- **Rendering mode** (F10): a progressive, path-traced view of your textures with multi-bounce
|
||||
light, environment importance sampling and one-click PNG save.
|
||||
light, environment importance sampling and one-click PNG save, traced on the GPU (compute
|
||||
shaders, desktop and WebGPU) or on the CPU.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/texturecraft-render.png" alt="A path-traced render of the material ball in worn red paint over bare steel, made with texturecraft-cli render --samples 256" width="80%">
|
||||
|
||||
+13
-13
@@ -13,16 +13,16 @@ end to end today (engine + UI + automation + tests), not what is planned.
|
||||
|---|---:|---:|---|---|
|
||||
| Project and files | 8 | 85% | New project from glTF/GLB, FBX (binary and ASCII 7.x), COLLADA, **USD (usda, usdc, usdz)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop, reimport mesh, image resources, remove unused resources, OBJ, textured GLB and **USD** mesh export, browser open/save/download | Alembic import; FBX 6; project templates; preserving strokes on reimport |
|
||||
| Texture sets | 6 | 80% | One set per material, **UDIM / UV tiles** (auto-detected, one texture per tile, `$udim` export), list with visibility, sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Per-tile resolution, converting a set to UV tiles after creation |
|
||||
| Layer stack | 16 | 82% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials | Anchor position inside a content stack; instances across texture sets of different resolutions |
|
||||
| Painting tools | 14 | 78% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z symmetry, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer), geometry decals, clone from the current layer only |
|
||||
| Materials and assets | 8 | 70% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 17 smart materials, 10 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | Filter library; dragging saved smart materials |
|
||||
| Layer stack | 16 | 92% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials | Layer effects beyond the filter library (Painter's full effect catalog) |
|
||||
| Painting tools | 14 | 85% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z symmetry, pen pressure, procedural and image alphas, **particle brush** | Pen tilt (not exposed by the windowing layer) |
|
||||
| Materials and assets | 8 | 80% | 48 procedural materials (incl. car paint, velvet, brushed steel, skin, wax), 17 smart materials, 10 smart masks, **67 procedural brush alphas**, 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | More filters (Painter ships dozens) |
|
||||
| Baking | 10 | 82% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel | Per-map ray settings, GPU ray-traced baking, high-poly material textures for the color map |
|
||||
| Viewport and display | 12 | 75% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, **path-traced Rendering mode** (F10) with environment importance sampling and an edge-aware **denoiser** | Subsurface scattering, depth of field, multiple cameras, GPU path tracing |
|
||||
| Shader | 6 | 75% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | Transmission/IOR, coat normal, screen-space subsurface blur |
|
||||
| Viewport and display | 12 | 88% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser** | Subsurface scattering, depth of field, multiple cameras |
|
||||
| Shader | 6 | 88% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | Transmission/IOR, coat normal, screen-space subsurface blur |
|
||||
| Export | 8 | 85% | 8 presets plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, `$udim` tiles, OBJ, textured GLB (with clearcoat/sheen) and USD mesh export, zip download in the browser | USD export of the new shader lobes |
|
||||
| UI and UX | 8 | 78% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave), saved UI layouts, **shortcut editor** with conflict detection, tooltips with shortcuts; all menu items live ([docs/parity.md](docs/parity.md)); progressive compositing keeps 4K and 8K sets responsive | Translations (the lookup is in place), remembering where a closed panel was |
|
||||
| Platforms | 4 | 60% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish |
|
||||
| **Total** | **100** | **≈ 78%** | | |
|
||||
| **Total** | **100** | **≈ 84%** | | |
|
||||
|
||||
Beyond Painter: every command is available to agents through MCP, the CLI and the app's
|
||||
control channel, and the whole engine runs headless.
|
||||
@@ -34,19 +34,19 @@ parallel on separate crates:
|
||||
|
||||
| Milestone | Scope | Estimate |
|
||||
|---|---|---:|
|
||||
| M1 Layer stack depth | Anchor position in content stacks, cross-resolution instances | 1 h |
|
||||
| M2 Tools | Geometry decals, clone from layer, pen tilt when the platform exposes it | 3 h |
|
||||
| M3 Assets | Filter library, dragging saved smart materials | 2 h |
|
||||
| M1 Layer stack depth | Done | 0 h |
|
||||
| M2 Tools | Pen tilt once the windowing layer reports it, decal drag handles | 1 h |
|
||||
| M3 Assets | Done | 0 h |
|
||||
| M4 Baking | Per-map ray settings, GPU ray-traced baking, high-poly material transfer | 3 h |
|
||||
| M5 Viewport | SSS, depth of field, cameras, GPU path tracing | 6 h |
|
||||
| M6 Shader | Transmission/IOR, coat normal, tessellated displacement | 2 h |
|
||||
| M5 Viewport | Refraction of other geometry, hardware ray tracing | 2 h |
|
||||
| M6 Shader | Tessellated displacement | 1 h |
|
||||
| M7 Formats | Alembic import, per-tile UDIM resolution | 3 h |
|
||||
| M8 UX | Translations, panel placement memory, more 8K tuning | 3 h |
|
||||
| M9 Release | First signed release on every platform, web deployment, README screenshots refresh | 4 h |
|
||||
| **Total** | | **≈ 27 h** |
|
||||
| **Total** | | **≈ 17 h** |
|
||||
|
||||
## Current focus
|
||||
|
||||
1. Viewport (M5): depth of field, multiple cameras, GPU path tracing.
|
||||
1. Viewport (M5): depth of field, multiple cameras.
|
||||
2. Baking (M4): per-map ray settings, GPU ray-traced baking.
|
||||
3. Release (M9): signing secrets on the repository, then the first release run.
|
||||
@@ -30,9 +30,10 @@ USAGE:
|
||||
texturecraft-cli export <input> <dir> [--preset <name>] [--format <ext>] [--padding <mode>] [--size <px>]
|
||||
Export textures (default preset: Document channels + Normal + AO).
|
||||
texturecraft-cli render <input> <out.png> [--size <W>x<H>] [--view 3d|2d] [--yaw <deg>] [--pitch <deg>]
|
||||
[--samples <n>] [--bounces <n>]
|
||||
Render the viewport to PNG (needs a GPU or software adapter); --samples path traces it on
|
||||
the CPU instead (Rendering mode).
|
||||
[--samples <n>] [--bounces <n>] [--cpu]
|
||||
Render the viewport to PNG (needs a GPU or software adapter); --samples path traces it
|
||||
instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on
|
||||
the CPU.
|
||||
texturecraft-cli new <mesh file | builtin:<id>> <out.tcraft> [--resolution <px>] [--sample]
|
||||
New project; --sample bakes and applies a smart material to every texture set.
|
||||
texturecraft-cli mcp [--bridge <port>] [--token <token>] [--read-root <dir>] [--write-root <dir>]
|
||||
@@ -54,7 +55,7 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
|
||||
("batch", &[], &[]),
|
||||
("bake", &["-o", "--resolution", "--maps"], &[]),
|
||||
("export", &["--preset", "--format", "--padding", "--size"], &[]),
|
||||
("render", &["--size", "--view", "--yaw", "--pitch", "--samples", "--bounces"], &[]),
|
||||
("render", &["--size", "--view", "--yaw", "--pitch", "--samples", "--bounces"], &["--cpu"]),
|
||||
("new", &["--resolution"], &["--sample"]),
|
||||
("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]),
|
||||
("serve", &["--port", "--read-root", "--write-root"], &[]),
|
||||
@@ -333,12 +334,14 @@ fn render(a: &Args) -> R {
|
||||
pitch: a.num("--pitch")?,
|
||||
samples: a.num("--samples")?,
|
||||
bounces: a.num("--bounces")?,
|
||||
cpu: a.has("--cpu"),
|
||||
};
|
||||
let mut h = open(input, None)?;
|
||||
let (w, ht, png) = h.render_png(&o).map_err(s)?;
|
||||
std::fs::write(out, png).map_err(|e| format!("cannot write {out}: {e}"))?;
|
||||
let by = if o.samples.is_some() { "path traced" } else { h.adapter().unwrap_or("GPU") };
|
||||
eprintln!("wrote {out} ({w}x{ht}, {by})");
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = h.render_png(&o).map_err(s)?;
|
||||
let secs = t0.elapsed().as_secs_f64();
|
||||
std::fs::write(out, &r.png).map_err(|e| format!("cannot write {out}: {e}"))?;
|
||||
eprintln!("wrote {out} ({}x{}, {}, {secs:.2} s)", r.width, r.height, r.by);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -117,12 +117,17 @@ fn render_writes_a_png() {
|
||||
fn path_traced_render_needs_no_gpu() {
|
||||
let d = tmp("trace");
|
||||
let out = d.join("ball.png");
|
||||
ok(&["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"]);
|
||||
let img = image::open(&out).unwrap().to_rgb8();
|
||||
assert_eq!(img.dimensions(), (96, 64));
|
||||
// The lit ball in the middle is brighter than the dark backdrop corner.
|
||||
let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::<u32>();
|
||||
assert!(lum(48, 28) > lum(1, 1) + 60);
|
||||
// On the GPU where it has compute shaders, then forced onto the CPU.
|
||||
for extra in [None, Some("--cpu")] {
|
||||
let mut args = vec!["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"];
|
||||
args.extend(extra);
|
||||
ok(&args);
|
||||
let img = image::open(&out).unwrap().to_rgb8();
|
||||
assert_eq!(img.dimensions(), (96, 64));
|
||||
// The lit ball in the middle is brighter than the dark backdrop corner.
|
||||
let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::<u32>();
|
||||
assert!(lum(48, 28) > lum(1, 1) + 60);
|
||||
}
|
||||
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1));
|
||||
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
|
||||
@@ -39,6 +39,16 @@ pub struct RenderOptions {
|
||||
pub samples: Option<u32>,
|
||||
/// Light bounces for path tracing (default 6).
|
||||
pub bounces: Option<u32>,
|
||||
/// Path trace on the CPU even when a GPU with compute shaders exists.
|
||||
pub cpu: bool,
|
||||
}
|
||||
|
||||
/// A PNG render and what drew it (the GPU adapter, or the CPU path tracer).
|
||||
pub struct Rendered {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub png: Vec<u8>,
|
||||
pub by: String,
|
||||
}
|
||||
|
||||
/// Most samples per pixel a path-traced render may take.
|
||||
@@ -233,8 +243,9 @@ impl Headless {
|
||||
Ok(json!({ "files": written, "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// Render the session to PNG: `(width, height, png)`. Errors without a GPU adapter.
|
||||
pub fn render_png(&mut self, o: &RenderOptions) -> Result<(u32, u32, Vec<u8>), AutomationError> {
|
||||
/// Render the session to PNG. The viewport needs a GPU adapter; path tracing (`samples`)
|
||||
/// runs on the GPU when it has compute shaders and falls back to the CPU.
|
||||
pub fn render_png(&mut self, o: &RenderOptions) -> Result<Rendered, AutomationError> {
|
||||
let s = &self.session;
|
||||
let kind = match o.view.as_deref().unwrap_or("3d") {
|
||||
"3d" => ViewKind::Scene,
|
||||
@@ -261,12 +272,34 @@ impl Headless {
|
||||
return Err(bad(format!("path tracing renders the 3D view with 1 to {MAX_TRACE_SAMPLES} samples")));
|
||||
}
|
||||
let settings = texturecraft_render::trace::TraceSettings { bounces: o.bounces.unwrap_or(6).clamp(1, 32) };
|
||||
let (w, h, rgba) = crate::render::path_trace(&mut self.session, size, camera, samples, &settings);
|
||||
let mut traced = None;
|
||||
let mut by = "CPU path tracer".to_string();
|
||||
if !o.cpu
|
||||
&& let Ok(gpu) = self.gpu.get_or_insert_with(Gpu::new)
|
||||
{
|
||||
// Last-resort guard, as for viewport renders below.
|
||||
let session = &mut self.session;
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.path_trace(session, size, camera, samples, &settings))) {
|
||||
Ok(Ok(px)) => {
|
||||
by = format!("{} (GPU path tracer)", gpu.adapter());
|
||||
traced = Some(px);
|
||||
}
|
||||
Ok(Err(e)) => by = format!("CPU path tracer ({e})"),
|
||||
Err(_) => {
|
||||
by = "CPU path tracer (the GPU path tracer failed)".into();
|
||||
self.gpu = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (w, h, rgba) = match traced {
|
||||
Some(px) => px,
|
||||
None => crate::render::path_trace(&mut self.session, size, camera, samples, &settings),
|
||||
};
|
||||
let png = encode_png(w, h, rgba)?;
|
||||
if !self.trusted() {
|
||||
check_png(png.len())?;
|
||||
}
|
||||
return Ok((w, h, png));
|
||||
return Ok(Rendered { width: w, height: h, png, by });
|
||||
}
|
||||
let gpu = match self.gpu.get_or_insert_with(Gpu::new) {
|
||||
Ok(g) => g,
|
||||
@@ -287,7 +320,7 @@ impl Headless {
|
||||
if !self.trusted() {
|
||||
check_png(png.len())?;
|
||||
}
|
||||
Ok((w, h, png))
|
||||
Ok(Rendered { width: w, height: h, png, by: self.adapter().unwrap_or("GPU").to_string() })
|
||||
}
|
||||
|
||||
/// The GPU adapter used for renders, if one was created.
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_engine::compose::{DisplayKind, all_tiles, tile_bytes};
|
||||
use texturecraft_engine::{Session, ViewMode};
|
||||
use texturecraft_render::gpu_trace::GpuTracer;
|
||||
use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer};
|
||||
use texturecraft_render::{Frame, Shade, ViewKind};
|
||||
|
||||
@@ -13,12 +14,14 @@ pub struct Gpu {
|
||||
mesh_id: u64,
|
||||
sets: Vec<((u32, u32), usize)>,
|
||||
env: String,
|
||||
/// The GPU path tracer, created by the first [`Gpu::path_trace`].
|
||||
tracer: Option<GpuTracer>,
|
||||
}
|
||||
|
||||
impl Gpu {
|
||||
/// Errors when there is no GPU (or software) adapter.
|
||||
pub fn new() -> Result<Gpu, String> {
|
||||
Ok(Gpu { h: texturecraft_render::headless::Headless::new()?, mesh_id: 0, sets: Vec::new(), env: String::new() })
|
||||
Ok(Gpu { h: texturecraft_render::headless::Headless::new()?, mesh_id: 0, sets: Vec::new(), env: String::new(), tracer: None })
|
||||
}
|
||||
|
||||
pub fn adapter(&self) -> &str {
|
||||
@@ -84,11 +87,30 @@ impl Gpu {
|
||||
let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() };
|
||||
self.h.render(&frame)
|
||||
}
|
||||
|
||||
/// [`path_trace`] on the GPU (compute shaders); errors when the adapter or the scene does
|
||||
/// not allow it.
|
||||
pub fn path_trace(
|
||||
&mut self,
|
||||
s: &mut Session,
|
||||
size: [u32; 2],
|
||||
camera: texturecraft_engine::geom::OrbitCamera,
|
||||
samples: u32,
|
||||
settings: &TraceSettings,
|
||||
) -> Result<(u32, u32, Vec<u8>), String> {
|
||||
self.sync(s);
|
||||
let (scene, display) = trace_inputs(s);
|
||||
let h = &self.h;
|
||||
let tracer = match &mut self.tracer {
|
||||
Some(t) => t,
|
||||
None => self.tracer.insert(GpuTracer::new(&h.device)?),
|
||||
};
|
||||
tracer.render(&h.device, &h.queue, &h.renderer, &scene, &camera, settings, &display, size, samples)
|
||||
}
|
||||
}
|
||||
|
||||
/// A progressive CPU path trace of the session's 3D view (the app's Rendering mode), finished
|
||||
/// after `samples` passes and denoised; RGBA8 (sRGB) pixels.
|
||||
pub fn path_trace(s: &mut Session, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera, samples: u32, settings: &TraceSettings) -> (u32, u32, Vec<u8>) {
|
||||
/// The session's 3D view as the path tracers see it, and how Rendering mode shows it (denoised).
|
||||
fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) {
|
||||
s.update();
|
||||
let sets = s
|
||||
.doc
|
||||
@@ -101,11 +123,24 @@ pub fn path_trace(s: &mut Session, size: [u32; 2], camera: texturecraft_engine::
|
||||
let d = &s.doc.project.display;
|
||||
let env_image = d.environment_resource().and_then(|n| s.images.get(n));
|
||||
let scene = TraceScene::for_display(s.mesh.clone(), s.bvh.clone(), sets, d, env_image.map(|i| i.as_ref()));
|
||||
(scene, TraceDisplay { denoise: true, ..TraceDisplay::from_display(d) })
|
||||
}
|
||||
|
||||
/// A progressive CPU path trace of the session's 3D view (the app's Rendering mode), finished
|
||||
/// after `samples` passes and denoised; RGBA8 (sRGB) pixels.
|
||||
pub fn path_trace(
|
||||
s: &mut Session,
|
||||
size: [u32; 2],
|
||||
camera: texturecraft_engine::geom::OrbitCamera,
|
||||
samples: u32,
|
||||
settings: &TraceSettings,
|
||||
) -> (u32, u32, Vec<u8>) {
|
||||
let (scene, display) = trace_inputs(s);
|
||||
let mut tracer = Tracer::new(size[0], size[1]);
|
||||
for _ in 0..samples {
|
||||
tracer.pass(&scene, &camera, settings);
|
||||
}
|
||||
(tracer.width, tracer.height, tracer.rgba8(&TraceDisplay { denoise: true, ..TraceDisplay::from_display(d) }))
|
||||
(tracer.width, tracer.height, tracer.rgba8(&display))
|
||||
}
|
||||
|
||||
/// How the viewport shades the session (the app's `viewport::shade`).
|
||||
@@ -122,7 +157,7 @@ pub fn shade(s: &Session) -> Shade {
|
||||
channel,
|
||||
// The app's default (only the 2D view draws it).
|
||||
wireframe: true,
|
||||
..Shade::from_display(&s.doc.project.display)
|
||||
..Shade::from_project(&s.doc.project)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,6 +201,35 @@ mod tests {
|
||||
assert!(warm(&lit) > warm(&base), "the orange sky warms the image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_path_trace_matches_the_cpu_on_the_material_ball() {
|
||||
let mesh = texturecraft_engine::geom::primitives::material_ball();
|
||||
let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap();
|
||||
execute(&mut s, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23], "roughness": 0.3, "metallic": 0.4})).unwrap();
|
||||
let Ok(mut gpu) = Gpu::new() else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return;
|
||||
};
|
||||
let (cam, settings, size) = (s.camera, TraceSettings { bounces: 4 }, [64, 48]);
|
||||
let g = match gpu.path_trace(&mut s, size, cam, 384, &settings) {
|
||||
Ok((_, _, px)) => px,
|
||||
Err(e) => {
|
||||
eprintln!("skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (_, _, c) = path_trace(&mut s, size, cam, 384, &settings);
|
||||
// Mean luminance per 8×8 block (8-bit levels) agrees.
|
||||
let lum = |img: &[u8], x: usize, y: usize| {
|
||||
let p = &img[(y * 64 + x) * 4..(y * 64 + x) * 4 + 3];
|
||||
0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32
|
||||
};
|
||||
let block = |img: &[u8], bx: usize, by: usize| (0..64).map(|i| lum(img, bx * 8 + i % 8, by * 8 + i / 8)).sum::<f32>() / 64.0;
|
||||
let worst = (0..6).flat_map(|by| (0..8).map(move |bx| (bx, by))).map(|(bx, by)| (block(&g, bx, by) - block(&c, bx, by)).abs()).fold(0.0, f32::max);
|
||||
assert!(worst < 4.0, "worst block differs by {worst} levels");
|
||||
assert!(g.chunks(4).any(|p| p[0] > p[2] + 40), "the orange fill shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_tile_atlas_renders_tiles_side_by_side() {
|
||||
let mesh = texturecraft_engine::geom::primitives::udim_plane();
|
||||
|
||||
@@ -93,9 +93,13 @@ impl Headless {
|
||||
pitch: f32_of(p, "pitch")?,
|
||||
samples: u32_of(p, "samples")?,
|
||||
bounces: u32_of(p, "bounces")?,
|
||||
cpu: match p.get("cpu") {
|
||||
None | Some(Value::Null) => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad("`cpu` must be true or false"))?,
|
||||
},
|
||||
};
|
||||
let (w, h, png) = self.render_png(&o)?;
|
||||
Ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) }))
|
||||
let r = self.render_png(&o)?;
|
||||
Ok(json!({ "width": r.width, "height": r.height, "by": r.by, "png": base64::engine::general_purpose::STANDARD.encode(r.png) }))
|
||||
}
|
||||
m if m.starts_with("ui.") || m == "viewport.screenshot" => {
|
||||
Err(bad(format!("`{m}` needs the running app (texturecraft --control <port>); headless renders use `render`")))
|
||||
|
||||
@@ -182,12 +182,16 @@ pub struct RenderParams {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub pitch: Option<f32>,
|
||||
/// Path trace the 3D view with this many samples per pixel (1..4096) instead of the
|
||||
/// real-time viewport: slower, physically based light transport, no GPU needed.
|
||||
/// real-time viewport: slower, physically based light transport; on the GPU when it has
|
||||
/// compute shaders, otherwise on the CPU (no GPU needed).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub samples: Option<u32>,
|
||||
/// Light bounces when path tracing (default 6).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub bounces: Option<u32>,
|
||||
/// Path trace on the CPU even when a GPU is available.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cpu: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
//! | Emissive | sRGB8 | emissive | | | scattering weight |
|
||||
//! | Lobes | RGBA8 | coat weight | coat roughness | anisotropy level | anisotropy angle |
|
||||
//! | Sheen | sRGB8 | sheen color | | | sheen weight |
|
||||
//! | Extra | RGBA8 | coat normal x | coat normal y | transmission | |
|
||||
//!
|
||||
//! Extra packs the coat normal's x and y as `128 + 127 × n` (the default normal is exactly 0;
|
||||
//! z is rebuilt in the shader).
|
||||
//!
|
||||
//! Alpha of sRGB formats is linear. Channels a set lacks pack their default values, which switch
|
||||
//! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a
|
||||
@@ -40,11 +44,21 @@ pub enum DisplayKind {
|
||||
Lobes,
|
||||
/// sRGB8: sheen color, alpha = sheen weight.
|
||||
Sheen,
|
||||
/// RGBA8 linear: coat normal x and y, transmission.
|
||||
Extra,
|
||||
}
|
||||
|
||||
impl DisplayKind {
|
||||
pub const ALL: [DisplayKind; 7] =
|
||||
[DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Normal, DisplayKind::Height, DisplayKind::Emissive, DisplayKind::Lobes, DisplayKind::Sheen];
|
||||
pub const ALL: [DisplayKind; 8] = [
|
||||
DisplayKind::BaseColor,
|
||||
DisplayKind::Orm,
|
||||
DisplayKind::Normal,
|
||||
DisplayKind::Height,
|
||||
DisplayKind::Emissive,
|
||||
DisplayKind::Lobes,
|
||||
DisplayKind::Sheen,
|
||||
DisplayKind::Extra,
|
||||
];
|
||||
|
||||
/// Bytes per texel of the upload format.
|
||||
pub fn bytes_per_texel(self) -> usize {
|
||||
@@ -60,6 +74,7 @@ impl DisplayKind {
|
||||
Channel::Emissive | Channel::ScatterWeight => DisplayKind::Emissive,
|
||||
Channel::CoatWeight | Channel::CoatRoughness | Channel::AnisotropyLevel | Channel::AnisotropyAngle => DisplayKind::Lobes,
|
||||
Channel::SheenColor | Channel::SheenWeight => DisplayKind::Sheen,
|
||||
Channel::CoatNormal | Channel::Transmission => DisplayKind::Extra,
|
||||
_ => DisplayKind::Orm,
|
||||
}
|
||||
}
|
||||
@@ -120,6 +135,18 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
|
||||
}
|
||||
}
|
||||
}
|
||||
DisplayKind::Extra => {
|
||||
let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission));
|
||||
// Signed 8-bit around 128 so the flat normal packs exactly.
|
||||
let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8;
|
||||
for (i, px) in out.chunks_exact_mut(4).enumerate() {
|
||||
for (k, d) in px.iter_mut().take(2).enumerate() {
|
||||
*d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v));
|
||||
}
|
||||
px[2] = transmission(i);
|
||||
px[3] = 0;
|
||||
}
|
||||
}
|
||||
DisplayKind::Orm => {
|
||||
let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel));
|
||||
// Specular/glossiness sets: the viewport shades roughness = 1 − glossiness.
|
||||
@@ -194,6 +221,7 @@ mod tests {
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]);
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1");
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]);
|
||||
assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission");
|
||||
for k in DisplayKind::ALL {
|
||||
assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]);
|
||||
}
|
||||
@@ -229,11 +257,14 @@ mod tests {
|
||||
set(Channel::SheenWeight, &[to_u16(0.8)]);
|
||||
set(Channel::SheenRoughness, &[to_u16(0.3)]);
|
||||
set(Channel::ScatterWeight, &[to_u16(0.4)]);
|
||||
set(Channel::Transmission, &[to_u16(0.6)]);
|
||||
set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]);
|
||||
let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec();
|
||||
let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1);
|
||||
assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes));
|
||||
assert!(near(&px(DisplayKind::Sheen), &[255, 0, 188, 204]), "{:?}", px(DisplayKind::Sheen));
|
||||
assert!(near(&px(DisplayKind::Normal)[3..], &[77]) && near(&px(DisplayKind::Emissive)[3..], &[102]));
|
||||
assert!(near(&px(DisplayKind::Extra), &[255, 128, 153, 0]), "{:?}", px(DisplayKind::Extra));
|
||||
for c in Channel::LOBES {
|
||||
assert_ne!(DisplayKind::of_channel(c), DisplayKind::Orm, "{c:?}");
|
||||
}
|
||||
|
||||
+333
-83
@@ -2,19 +2,20 @@
|
||||
//! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport
|
||||
//! and for export.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{
|
||||
BakedMap, BlendMode, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind,
|
||||
Mask, MaskBackground, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, hsl_adjust, lum, mix3,
|
||||
Mask, MaskBackground, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit,
|
||||
};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, to_u16, to_u16_signed};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
|
||||
|
||||
use crate::below::{Band, BelowCache, Level};
|
||||
use crate::pattern::{Coords, image_samples, procedural, world_noise};
|
||||
use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
|
||||
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
|
||||
|
||||
const NCH: usize = Channel::ALL.len();
|
||||
@@ -173,7 +174,7 @@ struct ChanPlan<'a> {
|
||||
comps: usize,
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
data: Option<&'a [u16]>,
|
||||
data: Option<Cow<'a, [u16]>>,
|
||||
/// Visible content effects, holding this channel's tile for paint effects (empty, and
|
||||
/// allocation free, for layers without content effects).
|
||||
effects: Vec<EffectPlan<'a>>,
|
||||
@@ -192,7 +193,7 @@ struct EffectPlan<'a> {
|
||||
kind: &'a EffectKind,
|
||||
blend: BlendMode,
|
||||
opacity: f32,
|
||||
data: Option<&'a [u16]>,
|
||||
data: Option<Cow<'a, [u16]>>,
|
||||
preview: bool,
|
||||
}
|
||||
|
||||
@@ -233,21 +234,128 @@ pub enum FieldKey {
|
||||
|
||||
pub type Fields = HashMap<FieldKey, Field>;
|
||||
|
||||
/// How a neighbourhood filter reads around a texel.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Op {
|
||||
/// Box blurs (≈ Gaussian), sharpening by the amount when given.
|
||||
Blur(Option<f32>),
|
||||
/// Average along a direction (unit vector in texels).
|
||||
Line([f32; 2]),
|
||||
/// Read at an offset given by a noise vector field.
|
||||
Warp { scale: f32, seed: u32 },
|
||||
/// Average downhill along a noise height field.
|
||||
Slope { scale: f32, seed: u32 },
|
||||
}
|
||||
|
||||
/// Index (among visible effects) of the last neighbourhood filter of an effect stack, its
|
||||
/// radius in texels and its sharpen amount.
|
||||
fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Option<f32>)> {
|
||||
/// radius in texels (`res` texels per UV tile across) and what it does.
|
||||
fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> {
|
||||
let texels = |v: f32| (v * res as f32 / 2048.0).max(0.5);
|
||||
effects
|
||||
.iter()
|
||||
.filter(|e| e.visible)
|
||||
.enumerate()
|
||||
.filter_map(|(i, e)| match &e.kind {
|
||||
EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, (radius * res as f32 / 2048.0).max(0.5), None)),
|
||||
EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Some(*amount))),
|
||||
EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, texels(*radius), Op::Blur(None))),
|
||||
EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))),
|
||||
EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => {
|
||||
let (sn, cs) = angle.to_radians().sin_cos();
|
||||
// Texel rows run down: positive angles turn counterclockwise on screen.
|
||||
Some((i, texels(*radius), Op::Line([cs, -sn])))
|
||||
}
|
||||
EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => {
|
||||
Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed }))
|
||||
}
|
||||
EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => {
|
||||
Some((i, texels(*radius), Op::Slope { scale: *scale, seed: *seed }))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.last()
|
||||
}
|
||||
|
||||
/// Samples along a directional or slope blur at most (beyond, samples spread out).
|
||||
const LINE_SAMPLES: i32 = 24;
|
||||
|
||||
/// Fractal noise over texel position `(x, y)` (`res` texels per UV unit, `scale` features per
|
||||
/// UV unit), shifted by `d` in noise space.
|
||||
fn texel_noise(x: f32, y: f32, d: [f32; 2], res: u32, scale: f32, seed: u32) -> f32 {
|
||||
let k = if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 } / res.max(1) as f32;
|
||||
noise::fbm([x * k + d[0], y * k + d[1], 0.0], 3, seed, noise::perlin)
|
||||
}
|
||||
|
||||
/// The neighbourhood filters that gather samples (directional and slope blur, warp) over a
|
||||
/// field region `(x0, y0, w, h)` of premultiplied `orig` texels (`comps` each) and their
|
||||
/// `cover`: bilinear samples weighted by coverage, so uncovered texels don't bleed in.
|
||||
/// Positions are absolute texel coordinates, so a texel's result does not depend on the region.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u32, u32, u32, u32), r: f32, res: u32, opacity: f32) -> Vec<f32> {
|
||||
let mut data = orig.to_vec();
|
||||
let (wu, hu) = (w as usize, h as usize);
|
||||
// Bilinear sample at absolute texel position (fx, fy) into `acc` (components, then weight).
|
||||
let sample = |fx: f32, fy: f32, acc: &mut [f32; 5]| {
|
||||
if !(fx.is_finite() && fy.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let (bx, by) = (fx.floor(), fy.floor());
|
||||
let (tx, ty) = (fx - bx, fy - by);
|
||||
for (dx, dy, k) in [(0, 0, (1.0 - tx) * (1.0 - ty)), (1, 0, tx * (1.0 - ty)), (0, 1, (1.0 - tx) * ty), (1, 1, tx * ty)] {
|
||||
let (cx, cy) = (bx as i64 + dx - i64::from(x0), by as i64 + dy - i64::from(y0));
|
||||
if k <= 0.0 || cx < 0 || cy < 0 || cx >= wu as i64 || cy >= hu as i64 {
|
||||
continue;
|
||||
}
|
||||
let i = cy as usize * wu + cx as usize;
|
||||
let (Some(c), Some(px)) = (cover.get(i), orig.get(i * comps..(i + 1) * comps)) else { continue };
|
||||
for (a, v) in acc.iter_mut().zip(px) {
|
||||
*a += v * k;
|
||||
}
|
||||
acc[4] += c * k;
|
||||
}
|
||||
};
|
||||
data.par_chunks_mut((comps * wu).max(1)).enumerate().for_each(|(row, line)| {
|
||||
for col in 0..wu {
|
||||
if cover.get(row * wu + col).is_none_or(|c| *c <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
let (x, y) = ((x0 as usize + col) as f32, (y0 as usize + row) as f32);
|
||||
let mut acc = [0.0f32; 5];
|
||||
let n = (r.ceil() as i32).clamp(1, LINE_SAMPLES);
|
||||
let step = r / n as f32;
|
||||
match op {
|
||||
Op::Line(d) => {
|
||||
for s in -n..=n {
|
||||
let t = s as f32 * step;
|
||||
sample(x + d[0] * t, y + d[1] * t, &mut acc);
|
||||
}
|
||||
}
|
||||
Op::Warp { scale, seed } => {
|
||||
let off = |salt: u32| ((texel_noise(x, y, [0.0; 2], res, scale, seed ^ salt) - 0.5) * 3.0).clamp(-1.0, 1.0) * r;
|
||||
sample(x + off(0), y + off(0x5BD1_E995), &mut acc);
|
||||
}
|
||||
Op::Slope { scale, seed } => {
|
||||
let e = 0.01;
|
||||
let hgt = |dx: f32, dy: f32| texel_noise(x, y, [dx, dy], res, scale, seed);
|
||||
// Downhill; a flat spot keeps its value.
|
||||
let d = Vec2::new(hgt(-e, 0.0) - hgt(e, 0.0), hgt(0.0, -e) - hgt(0.0, e)).try_normalize().unwrap_or(Vec2::ZERO);
|
||||
for s in 0..=n {
|
||||
let t = s as f32 * step;
|
||||
sample(x + d.x * t, y + d.y * t, &mut acc);
|
||||
}
|
||||
}
|
||||
Op::Blur(_) => {}
|
||||
}
|
||||
if acc[4] > 1e-6
|
||||
&& let Some(px) = line.get_mut(col * comps..(col + 1) * comps)
|
||||
{
|
||||
for (slot, a) in px.iter_mut().zip(acc) {
|
||||
*slot += (a / acc[4] - *slot) * opacity;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
data
|
||||
}
|
||||
|
||||
/// Fixed-point scale of the blur. Integer running sums make a texel's result independent of
|
||||
/// the region it is computed in, so tiles composited in any grouping agree exactly.
|
||||
const FIX: f64 = (1u64 << 24) as f64;
|
||||
@@ -367,12 +475,13 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
|
||||
Job::Mask(m) => &m.effects,
|
||||
Job::Content(_) => &inp.project.content_layer(id)?.content_effects,
|
||||
};
|
||||
let (k, radius, sharpen) = neighbourhood(effects, inp.tile_res())?;
|
||||
let (k, radius, op) = neighbourhood(effects, inp.tile_res())?;
|
||||
let opacity = effects.iter().filter(|e| e.visible).nth(k).map(|e| e.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
|
||||
// Clamped: a hostile radius must not overflow the halo and window arithmetic.
|
||||
let r = radius.round().clamp(1.0, gw.max(gh) as f32) as u32;
|
||||
// Three box passes reach 3r texels.
|
||||
let halo = (3 * r).div_ceil(TILE);
|
||||
// Three box passes reach 3r texels, the other filters r (and a texel for bilinear samples).
|
||||
let reach = if let Op::Blur(_) = op { 3 * r } else { r + 1 };
|
||||
let halo = reach.div_ceil(TILE);
|
||||
let (tx0, ty0) = tiles.iter().fold((u32::MAX, u32::MAX), |(a, b), t| (a.min(t.0), b.min(t.1)));
|
||||
let (tx1, ty1) = tiles.iter().fold((0, 0), |(a, b), t| (a.max(t.0), b.max(t.1)));
|
||||
let (rx0, ry0) = (tx0.saturating_sub(halo) * TILE, ty0.saturating_sub(halo) * TILE);
|
||||
@@ -442,6 +551,14 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
|
||||
}
|
||||
}
|
||||
});
|
||||
let sharpen = match op {
|
||||
Op::Blur(sharpen) => sharpen,
|
||||
_ => {
|
||||
let mut data = gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, inp.tile_res(), opacity);
|
||||
unpremultiply(&mut data, comps);
|
||||
return Some(Field { x0: rx0, y0: ry0, w, h, comps, data });
|
||||
}
|
||||
};
|
||||
// Weighted so uncovered texels don't bleed in.
|
||||
let (wu, hu, ru) = (w as usize, h as usize, r as usize);
|
||||
let mut weights = cover;
|
||||
@@ -463,6 +580,12 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
|
||||
}
|
||||
});
|
||||
}
|
||||
unpremultiply(&mut data, comps);
|
||||
Some(Field { x0: rx0, y0: ry0, w, h, comps, data })
|
||||
}
|
||||
|
||||
/// Clamp filtered masks to 0..1, and turn filtered content back into straight values.
|
||||
fn unpremultiply(data: &mut [f32], comps: usize) {
|
||||
data.par_chunks_mut(comps).for_each(|px| match px {
|
||||
[v] => *v = v.clamp(0.0, 1.0),
|
||||
[r, g, b, cov] => {
|
||||
@@ -474,7 +597,6 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
Some(Field { x0: rx0, y0: ry0, w, h, comps, data })
|
||||
}
|
||||
|
||||
/// Precompute the neighbourhood-filtered masks and content channels of every layer that needs
|
||||
@@ -518,8 +640,9 @@ struct Node<'a> {
|
||||
content: Content<'a>,
|
||||
chans: Vec<ChanPlan<'a>>,
|
||||
mask: Option<MaskPlan<'a>>,
|
||||
/// Visible anchor points of the layer (recorded after it is applied).
|
||||
anchors: Vec<LayerId>,
|
||||
/// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an
|
||||
/// anchor with visible effects above it) with its content cut after `k` visible effects.
|
||||
anchors: Vec<(LayerId, Option<usize>)>,
|
||||
/// The node or one of its children records an anchor.
|
||||
has_anchor: bool,
|
||||
height_mask: HeightMask,
|
||||
@@ -540,13 +663,36 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c
|
||||
kind: &e.kind,
|
||||
blend: e.blend,
|
||||
opacity: e.opacity,
|
||||
data: matches!(e.kind, EffectKind::Paint).then(|| img.filter(|i| i.width() == inp.gbuf.width).and_then(|i| i.tile(tx, ty))).flatten(),
|
||||
preview: inp.preview.is_some_and(|p| p.target == target),
|
||||
data: if matches!(e.kind, EffectKind::Paint) { tile_of(inp, img, tx, ty, channel) } else { None },
|
||||
preview: previews(inp, target),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the live stroke paints `target` in this composite (a stroke on a layer instanced in a
|
||||
/// set of another size does not show there).
|
||||
fn previews(inp: &Inputs, target: PaintTarget) -> bool {
|
||||
inp.preview.is_some_and(|p| p.target == target && (p.alpha.width(), p.alpha.height()) == (inp.gbuf.width, inp.gbuf.height))
|
||||
}
|
||||
|
||||
/// Tile (tx, ty) of painted pixels `img` (of `channel`, or a mask when None) at the size of the
|
||||
/// set being composited: as stored, or resampled (bilinear, premultiplied) when the pixels
|
||||
/// belong to a layer instanced from a set of another resolution.
|
||||
fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, channel: Option<Channel>) -> Option<Cow<'a, [u16]>> {
|
||||
let img = img?;
|
||||
let (w, h) = (inp.gbuf.width, inp.gbuf.height);
|
||||
if (img.width(), img.height()) == (w, h) {
|
||||
return img.tile(tx, ty).map(Cow::Borrowed);
|
||||
}
|
||||
// Empty texels of signed channels hold a signed zero.
|
||||
let empty: Vec<u16> = match channel {
|
||||
Some(c) if c.kind() == ChannelKind::Signed => [vec![to_u16_signed(0.0); c.components()], vec![0]].concat(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
img.resampled_tile(w, h, tx, ty, &empty).map(Cow::Owned)
|
||||
}
|
||||
|
||||
fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option<MaskPlan<'a>> {
|
||||
if !mask.enabled {
|
||||
return None;
|
||||
@@ -567,7 +713,16 @@ fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, t
|
||||
/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are
|
||||
/// planned when `kids`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn plan_node<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>, kids: bool) -> Option<Node<'a>> {
|
||||
fn plan_node<'a>(
|
||||
inp: &Inputs<'a>,
|
||||
id: LayerId,
|
||||
channels: &[Channel],
|
||||
tx: u32,
|
||||
ty: u32,
|
||||
depth: usize,
|
||||
fields: Option<&'a Fields>,
|
||||
kids: bool,
|
||||
) -> Option<Node<'a>> {
|
||||
let own: &'a Layer = inp.project.layers.get(&id)?;
|
||||
// Instances draw their source's content (a missing source draws nothing).
|
||||
let layer: &'a Layer = inp.project.content_layer(id)?;
|
||||
@@ -584,16 +739,14 @@ fn plan_node<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, t
|
||||
if b.mode == BlendMode::Disable || b.opacity <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
// shortcut: an instance in a set of another resolution draws no painted pixels;
|
||||
// resample the source's pixels if instances across sizes become common.
|
||||
let data = if paint { inp.pixels.layer(layer.id, *c).filter(|img| img.width() == inp.gbuf.width).and_then(|img| img.tile(tx, ty)) } else { None };
|
||||
let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None };
|
||||
let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c)) } else { Vec::new() };
|
||||
let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c))));
|
||||
Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start })
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let content = match &layer.kind {
|
||||
LayerKind::Paint => Content::Paint { preview: inp.preview.is_some_and(|p| p.target == PaintTarget::Layer(layer.id)) },
|
||||
LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) },
|
||||
LayerKind::Fill(f) => Content::Fill(f),
|
||||
LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }),
|
||||
// `content_layer` already followed instance links.
|
||||
@@ -610,12 +763,20 @@ fn plan_node<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, t
|
||||
return None;
|
||||
}
|
||||
let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields));
|
||||
let anchors: Vec<LayerId> =
|
||||
if fx { layer.content_effects.iter().filter(|e| e.visible && matches!(e.kind, EffectKind::Anchor)).map(|e| e.id).collect() } else { Vec::new() };
|
||||
let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() };
|
||||
let has_anchor = !anchors.is_empty() || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor));
|
||||
Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask })
|
||||
}
|
||||
|
||||
/// The visible anchor points of a content stack with where they cut it: after their index among
|
||||
/// the visible effects, or None for anchors with only anchors above them (they record the
|
||||
/// layer's full result).
|
||||
fn anchor_cuts(effects: &[Effect]) -> Vec<(LayerId, Option<usize>)> {
|
||||
let visible: Vec<&Effect> = effects.iter().filter(|e| e.visible).collect();
|
||||
let last = visible.iter().rposition(|e| !matches!(e.kind, EffectKind::Anchor));
|
||||
visible.iter().enumerate().filter(|(_, e)| matches!(e.kind, EffectKind::Anchor)).map(|(i, e)| (e.id, last.filter(|l| *l > i).map(|_| i))).collect()
|
||||
}
|
||||
|
||||
/// One level of the path to the hot layer (see [`Level`]) planned for a tile.
|
||||
struct LevelPlan<'a> {
|
||||
below: Vec<Node<'a>>,
|
||||
@@ -639,16 +800,6 @@ fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx:
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Apply a 0..1 function to each component of a channel value: signed values map through
|
||||
/// 0..1, normals are left alone.
|
||||
fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] {
|
||||
match kind {
|
||||
ChannelKind::NormalMap => v,
|
||||
ChannelKind::Signed => v.map(|x| f(x * 0.5 + 0.5) * 2.0 - 1.0),
|
||||
ChannelKind::Color | ChannelKind::Scalar => v.map(f),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn blend_chan(c: &ChanPlan, mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
|
||||
if c.comps == 3 { blend3(mode, a, b) } else { [blend1(mode, a[0], b[0]); 3] }
|
||||
@@ -664,6 +815,9 @@ fn over(c: &ChanPlan, mode: BlendMode, v: [f32; 3], cov: f32, p: [f32; 3], a: f3
|
||||
(mix3(v, b, a / nc.max(1e-5)), nc)
|
||||
}
|
||||
|
||||
/// The plain UV projection a decal's frame coordinates are sampled through.
|
||||
const DECAL_UV: Projection = Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] };
|
||||
|
||||
/// Per-texel context.
|
||||
struct Texel<'a, 'b> {
|
||||
inp: &'b Inputs<'a>,
|
||||
@@ -791,17 +945,44 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
self.inp.baked.scalar(m, self.x, self.y, self.res)
|
||||
}
|
||||
|
||||
/// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its
|
||||
/// position in the decal's frame (then sampled as UVs) and the decal's coverage.
|
||||
fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) {
|
||||
let c = self.coords();
|
||||
match proj {
|
||||
Projection::Decal(d) => match self.world().and_then(|p| decal_uv(d, p, c.nrm)) {
|
||||
Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w),
|
||||
None => (c, &DECAL_UV, 0.0),
|
||||
},
|
||||
_ => (c, proj, 1.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a fill projected by `proj` covers this texel: 1, or for a decal its frame
|
||||
/// coverage times the alpha of its first image source.
|
||||
fn cover<'s>(&mut self, mut sources: impl Iterator<Item = &'s Source>, proj: &Projection) -> f32 {
|
||||
if !matches!(proj, Projection::Decal(_)) {
|
||||
return 1.0;
|
||||
}
|
||||
let (c, _, w) = self.projected(proj);
|
||||
let image = sources.find_map(|s| match s {
|
||||
Source::Image { name } => self.inp.images.get(name),
|
||||
_ => None,
|
||||
});
|
||||
w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] {
|
||||
match s {
|
||||
Source::Uniform(v) => *v,
|
||||
Source::Procedural { pattern, low, high } => {
|
||||
let c = self.coords();
|
||||
let (c, proj, _) = self.projected(proj);
|
||||
let t = procedural(pattern, proj, &c);
|
||||
mix3(*low, *high, t)
|
||||
}
|
||||
Source::Image { name } => {
|
||||
let Some(img) = self.inp.images.get(name) else { return [0.5; 3] };
|
||||
let c = self.coords();
|
||||
let (c, proj, _) = self.projected(proj);
|
||||
let mut acc = [0.0f32; 4];
|
||||
for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) {
|
||||
let s = img.sample(uv.x, uv.y);
|
||||
@@ -858,7 +1039,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
let o = e.opacity.clamp(0.0, 1.0);
|
||||
match e.kind {
|
||||
EffectKind::Paint => {
|
||||
let (mut pv, mut cov) = match e.data {
|
||||
let (mut pv, mut cov) = match e.data.as_deref() {
|
||||
Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))),
|
||||
None => (0.0, 0.0),
|
||||
};
|
||||
@@ -881,7 +1062,7 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
}
|
||||
EffectKind::Fill { source, projection } => {
|
||||
let val = self.source(source, projection, ChannelKind::Scalar)[0];
|
||||
v += (blend1(e.blend, v, val) - v) * o;
|
||||
v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection);
|
||||
}
|
||||
EffectKind::Generator(g) => {
|
||||
let val = self.generator(g);
|
||||
@@ -889,20 +1070,9 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
}
|
||||
EffectKind::Levels(l) => v += (l.apply(v) - v) * o,
|
||||
EffectKind::Filter(f) => {
|
||||
let val = match f {
|
||||
Filter::Invert => 1.0 - v,
|
||||
Filter::Threshold { level } => {
|
||||
if v >= *level {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
}
|
||||
// A mask is gray: only its lightness changes.
|
||||
Filter::Hsl { lightness, .. } => hsl_adjust([v; 3], 0.0, 0.0, *lightness)[0],
|
||||
// Neighbourhood filters come precomputed through `MaskPlan::start`.
|
||||
Filter::Blur { .. } | Filter::Sharpen { .. } => v,
|
||||
};
|
||||
// A mask is gray (HSL only changes its lightness); neighbourhood filters come
|
||||
// precomputed through `MaskPlan::start`.
|
||||
let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]);
|
||||
v += (val - v) * o;
|
||||
}
|
||||
EffectKind::ColorSelection { colors, tolerance } => {
|
||||
@@ -948,15 +1118,32 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
}
|
||||
}
|
||||
Content::Fill(_) | Content::Paint { .. } if m > 0.0 => {
|
||||
let before = if n.anchors.iter().any(|a| a.1.is_some()) { Some(*acc) } else { None };
|
||||
for c in &n.chans {
|
||||
if let Some((v, cov)) = self.tape_content(&n.content, c) {
|
||||
apply(acc, c, v, cov, m);
|
||||
}
|
||||
}
|
||||
// Anchors inside the content stack: the stack with the content cut there.
|
||||
for (a, cut) in &n.anchors {
|
||||
let rec = match (cut, before) {
|
||||
(Some(k), Some(mut b)) => {
|
||||
for c in &n.chans {
|
||||
if let Some((v, cov)) = self.content_to(&n.content, c, *k) {
|
||||
apply(&mut b, c, v, cov, m);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
_ => *acc,
|
||||
};
|
||||
self.anchors.push((*a, rec));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
for a in &n.anchors {
|
||||
for (a, _) in &n.anchors {
|
||||
self.anchors.push((*a, *acc));
|
||||
}
|
||||
}
|
||||
@@ -1049,7 +1236,13 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
/// Straight value and coverage of one channel of a paint or fill layer at this texel
|
||||
/// (content effects and live stroke preview included). None where the layer is empty.
|
||||
fn content(&mut self, content: &Content, c: &ChanPlan) -> Option<([f32; 3], f32)> {
|
||||
let (mut v, mut cov, skip) = match c.start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) {
|
||||
self.content_to(content, c, usize::MAX)
|
||||
}
|
||||
|
||||
/// [`Texel::content`] with only the first `end` visible content effects.
|
||||
fn content_to(&mut self, content: &Content, c: &ChanPlan, end: usize) -> Option<([f32; 3], f32)> {
|
||||
let start = c.start.filter(|(k, _)| *k < end);
|
||||
let (mut v, mut cov, skip) = match start.and_then(|(k, f)| f.get(self.x, self.y).map(|d| (k, d))) {
|
||||
Some((k, d)) => {
|
||||
let px = |i: usize| d.get(i).copied().unwrap_or(0.0);
|
||||
([px(0), px(1), px(2)], px(3), k + 1)
|
||||
@@ -1063,15 +1256,15 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
Some(s) => self.source(s, &f.projection, ch.kind()),
|
||||
None => ch.default_value(),
|
||||
};
|
||||
(v, 1.0)
|
||||
(v, self.cover(f.sources.values(), &f.projection))
|
||||
}
|
||||
Content::Paint { preview } => self.painted(c.data, c, *preview),
|
||||
Content::Paint { preview } => self.painted(c.data.as_deref(), c, *preview),
|
||||
Content::Group(_) => return None,
|
||||
};
|
||||
(v, cov, 0)
|
||||
}
|
||||
};
|
||||
for e in c.effects.iter().skip(skip) {
|
||||
for e in c.effects.iter().take(end).skip(skip) {
|
||||
(v, cov) = self.content_effect(e, c, v, cov);
|
||||
}
|
||||
(cov > 0.0).then_some((v, cov.min(1.0)))
|
||||
@@ -1138,32 +1331,24 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
let o = e.opacity.clamp(0.0, 1.0);
|
||||
match e.kind {
|
||||
EffectKind::Paint => {
|
||||
let (p, pc) = self.painted(e.data, c, e.preview);
|
||||
let (p, pc) = self.painted(e.data.as_deref(), c, e.preview);
|
||||
over(c, e.blend, v, cov, p, pc * o)
|
||||
}
|
||||
EffectKind::Material(f) => match Channel::ALL.get(c.ch).and_then(|ch| f.sources.get(ch).map(|s| (*ch, s))) {
|
||||
Some((ch, s)) => {
|
||||
let p = self.source(s, &f.projection, ch.kind());
|
||||
over(c, e.blend, v, cov, p, o)
|
||||
let w = o * self.cover(f.sources.values(), &f.projection);
|
||||
over(c, e.blend, v, cov, p, w)
|
||||
}
|
||||
None => (v, cov),
|
||||
},
|
||||
EffectKind::Levels(l) => (mix3(v, per_unit(c.kind, v, |x| l.apply(x)), o), cov),
|
||||
EffectKind::Filter(f) => {
|
||||
let out = match f {
|
||||
Filter::Invert => per_unit(c.kind, v, |x| 1.0 - x),
|
||||
Filter::Threshold { level } => per_unit(c.kind, v, |x| if x >= *level { 1.0 } else { 0.0 }),
|
||||
Filter::Hsl { hue, saturation, lightness } => match c.kind {
|
||||
ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness),
|
||||
_ => per_unit(c.kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]),
|
||||
},
|
||||
// Neighbourhood filters come precomputed through `ChanPlan::start`.
|
||||
Filter::Blur { .. } | Filter::Sharpen { .. } => v,
|
||||
};
|
||||
(mix3(v, out, o), cov)
|
||||
}
|
||||
// Neighbourhood filters come precomputed through `ChanPlan::start`.
|
||||
EffectKind::Filter(f) => (f.point(c.kind, v).map_or(v, |out| mix3(v, out, o)), cov),
|
||||
// Anchors are recorded by `eval`; mask-only effects leave content as it is.
|
||||
EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => (v, cov),
|
||||
EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => {
|
||||
(v, cov)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1587,11 +1772,8 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<
|
||||
let nodes = plan(&solo_inp, &[id], &channels, tx, ty, 0, Some(&fields));
|
||||
let Some(n) = nodes.first() else { return Vec::new() };
|
||||
let full = anchor_plan(&solo_inp, id, &channels, tx, ty, Some(&fields));
|
||||
let mut bufs: Vec<(Channel, Vec<u16>, bool)> = n
|
||||
.chans
|
||||
.iter()
|
||||
.filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false)))
|
||||
.collect();
|
||||
let mut bufs: Vec<(Channel, Vec<u16>, bool)> =
|
||||
n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect();
|
||||
for (ch, buf, _) in &mut bufs {
|
||||
if ch.kind() == ChannelKind::Signed {
|
||||
for px in buf.chunks_exact_mut(2) {
|
||||
@@ -1652,7 +1834,17 @@ mod tests {
|
||||
|
||||
fn run(f: &Fixture, preview: Option<&StrokePreview>) -> Composite {
|
||||
let images = Default::default();
|
||||
let inp = Inputs { project: &f.project, ts: 0, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, preview, images: &images, bounds: f.mesh.bounds() };
|
||||
let inp = Inputs {
|
||||
project: &f.project,
|
||||
ts: 0,
|
||||
mesh: &f.mesh,
|
||||
gbuf: &f.gbuf,
|
||||
pixels: &f.pixels,
|
||||
baked: &f.baked,
|
||||
preview,
|
||||
images: &images,
|
||||
bounds: f.mesh.bounds(),
|
||||
};
|
||||
let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64);
|
||||
composite_tiles(&inp, &mut out, &all_tiles(64, 64));
|
||||
out
|
||||
@@ -1753,7 +1945,10 @@ mod tests {
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
let pattern = Procedural::new(ProceduralKind::Checker);
|
||||
let (e1, e2) = (f.project.alloc_id(), f.project.alloc_id());
|
||||
mask.effects.push(Effect::new(e1, EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }));
|
||||
mask.effects.push(Effect::new(
|
||||
e1,
|
||||
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() },
|
||||
));
|
||||
f.project.layer_mut(id).unwrap().mask = Some(mask.clone());
|
||||
let hard: Vec<f32> = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect();
|
||||
mask.effects.push(Effect::new(e2, EffectKind::Filter(Filter::Blur { radius: 64.0 })));
|
||||
@@ -1761,8 +1956,11 @@ mod tests {
|
||||
let soft_img = run(&f, None);
|
||||
let soft: Vec<f32> = (0..64).map(|x| soft_img.value(Channel::BaseColor, x, 20)[0]).collect();
|
||||
let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.55 && **x < 0.95).count();
|
||||
assert!(mids(&soft) > mids(&hard) + 4, "hard {hard:?}
|
||||
soft {soft:?}");
|
||||
assert!(
|
||||
mids(&soft) > mids(&hard) + 4,
|
||||
"hard {hard:?}
|
||||
soft {soft:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1866,7 +2064,17 @@ soft {soft:?}");
|
||||
assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]), "channels without a source stay untouched");
|
||||
// Flattening bakes the content effects in.
|
||||
let images = Default::default();
|
||||
let inp = Inputs { project: &f.project, ts: 0, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, preview: None, images: &images, bounds: f.mesh.bounds() };
|
||||
let inp = Inputs {
|
||||
project: &f.project,
|
||||
ts: 0,
|
||||
mesh: &f.mesh,
|
||||
gbuf: &f.gbuf,
|
||||
pixels: &f.pixels,
|
||||
baked: &f.baked,
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: f.mesh.bounds(),
|
||||
};
|
||||
let flat = flatten_layer(&inp, id, &all_tiles(64, 64)).unwrap();
|
||||
assert!(flat.iter().all(|(c, _, _)| *c == Channel::Roughness));
|
||||
let (_, _, data) = flat.iter().find(|(_, t, _)| *t == (0, 0)).unwrap();
|
||||
@@ -1897,6 +2105,48 @@ soft {soft:?}");
|
||||
assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decal_fills_cover_only_their_frame_and_image_alpha() {
|
||||
let mut f = fixture();
|
||||
let s = f.gbuf.surface(&f.mesh, 32 * 64 + 32).unwrap();
|
||||
let d = texturecraft_core::Decal {
|
||||
center: s.pos.to_array(),
|
||||
normal: s.nrm.to_array(),
|
||||
up: s.nrm.any_orthonormal_vector().to_array(),
|
||||
size: [1.0, 1.0],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 0.5,
|
||||
};
|
||||
let id = f.project.alloc_id();
|
||||
let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() };
|
||||
fill.sources.insert(Channel::BaseColor, Source::Image { name: "decal".into() });
|
||||
f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
|
||||
let composite = |alpha: f32| {
|
||||
let img = crate::store::ImageRes { width: 2, height: 2, rgba: vec![[1.0, 0.0, 0.0, alpha]; 4], srgb: false };
|
||||
let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect();
|
||||
let inp = Inputs {
|
||||
project: &f.project,
|
||||
ts: 0,
|
||||
mesh: &f.mesh,
|
||||
gbuf: &f.gbuf,
|
||||
pixels: &f.pixels,
|
||||
baked: &f.baked,
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: f.mesh.bounds(),
|
||||
};
|
||||
let mut out = Composite::new(&f.project.texture_sets[0].channel_list(), 64);
|
||||
composite_tiles(&inp, &mut out, &all_tiles(64, 64));
|
||||
out
|
||||
};
|
||||
let out = composite(1.0);
|
||||
assert!(close(out.value(Channel::BaseColor, 32, 32), [1.0, 0.0, 0.0]), "{:?}", out.value(Channel::BaseColor, 32, 32));
|
||||
assert!(close(out.value(Channel::BaseColor, 2, 2), [0.5; 3]), "outside the frame");
|
||||
let half = composite(0.5);
|
||||
assert!(close(half.value(Channel::BaseColor, 32, 32), [0.75, 0.25, 0.25]), "the image alpha shapes the decal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_read_colors_as_gray_in_fill_layers() {
|
||||
let mut f = fixture();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Procedural patterns and projections.
|
||||
|
||||
use texturecraft_core::{Procedural, ProceduralKind, Projection};
|
||||
use texturecraft_core::{Decal, Procedural, ProceduralKind, Projection};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_texel::noise;
|
||||
|
||||
@@ -199,6 +199,8 @@ pub fn procedural(pr: &Procedural, proj: &Projection, c: &Coords) -> f32 {
|
||||
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
|
||||
raw(pr.kind, Vec3::new(u * 4.0, h, 0.0) * *scale * s, pr.seed)
|
||||
}
|
||||
// `c.uv` is already in the decal's frame (see [`decal_uv`]).
|
||||
Projection::Decal(_) => raw(pr.kind, (c.uv * s).extend(0.0), pr.seed),
|
||||
};
|
||||
shape(pr, v)
|
||||
}
|
||||
@@ -244,9 +246,48 @@ pub fn image_samples(proj: &Projection, c: &Coords) -> [(Vec2, f32); 3] {
|
||||
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
|
||||
one(Vec2::new(u, 0.5 - h * 0.5) * *scale)
|
||||
}
|
||||
Projection::Decal(_) => one(c.uv),
|
||||
}
|
||||
}
|
||||
|
||||
/// A decal's frame: origin (center plus offset), unit right, up and normal (None when degenerate).
|
||||
pub fn decal_axes(d: &Decal) -> Option<(Vec3, Vec3, Vec3, Vec3)> {
|
||||
if !d.size.iter().all(|v| v.is_finite() && *v > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let n = Vec3::from(d.normal).try_normalize()?;
|
||||
let up0 = (Vec3::from(d.up) - n * n.dot(Vec3::from(d.up))).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector());
|
||||
let right0 = up0.cross(n);
|
||||
let origin = Vec3::from(d.center) + right0 * d.offset[0] + up0 * d.offset[1];
|
||||
let (sn, cs) = d.rotation.to_radians().sin_cos();
|
||||
let right = right0 * cs + up0 * sn;
|
||||
let up = up0 * cs - right0 * sn;
|
||||
origin.is_finite().then_some((origin, right, up, n))
|
||||
}
|
||||
|
||||
/// The decal's corners in world space (top left, top right, bottom right, bottom left).
|
||||
pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> {
|
||||
let (o, r, u, _) = decal_axes(d)?;
|
||||
let (hw, hh) = (d.size[0] * 0.5, d.size[1] * 0.5);
|
||||
Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh])
|
||||
}
|
||||
|
||||
/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates
|
||||
/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its
|
||||
/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit.
|
||||
pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
|
||||
let (o, r, u, n) = decal_axes(d)?;
|
||||
let facing = nrm.dot(n);
|
||||
let q = p - o;
|
||||
let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs());
|
||||
let depth = d.depth.max(1e-6);
|
||||
if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz));
|
||||
Some((Vec2::new(lx + 0.5, 0.5 - ly), w))
|
||||
}
|
||||
|
||||
/// World-space noise used by generators (seamless across UV islands).
|
||||
pub fn world_noise(pos: Vec3, scale: f32, seed: u32) -> f32 {
|
||||
noise::fbm((pos * scale.max(1e-3)).to_array(), 4, seed, noise::perlin)
|
||||
@@ -264,6 +305,15 @@ mod tests {
|
||||
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
|
||||
Projection::Spherical { scale: 1.0 },
|
||||
Projection::Cylindrical { scale: 1.0, axis: 1 },
|
||||
Projection::Decal(Decal {
|
||||
center: [0.0; 3],
|
||||
normal: [0.0, 0.0, 1.0],
|
||||
up: [0.0, 1.0, 0.0],
|
||||
size: [1.0; 2],
|
||||
rotation: 0.0,
|
||||
offset: [0.0; 2],
|
||||
depth: 1.0,
|
||||
}),
|
||||
];
|
||||
for k in ProceduralKind::ALL {
|
||||
let pr = Procedural::new(k);
|
||||
@@ -282,6 +332,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decals_cover_their_frame_facing_them() {
|
||||
let d = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [2.0, 1.0], rotation: 0.0, offset: [0.0; 2], depth: 0.5 };
|
||||
let z = Vec3::Z;
|
||||
let (uv, w) = decal_uv(&d, Vec3::new(0.5, 0.25, 0.0), z).unwrap();
|
||||
assert!((uv - Vec2::new(0.75, 0.25)).length() < 1e-5 && (w - 1.0).abs() < 1e-5, "{uv} {w}");
|
||||
assert!(decal_uv(&d, Vec3::new(1.1, 0.0, 0.0), z).is_none(), "outside the frame");
|
||||
assert!(decal_uv(&d, Vec3::ZERO, -z).is_none(), "back faces");
|
||||
assert!(decal_uv(&d, Vec3::new(0.0, 0.0, 0.6), z).is_none(), "beyond the depth");
|
||||
// Rotated a quarter turn and shifted: the frame turns with it.
|
||||
let r = Decal { rotation: 90.0, offset: [1.0, 0.0], ..d };
|
||||
let (uv, _) = decal_uv(&r, Vec3::new(1.0, 0.9, 0.0), z).unwrap();
|
||||
assert!((uv.x - 0.95).abs() < 1e-4 && (uv.y - 0.5).abs() < 1e-4, "{uv}");
|
||||
let c = decal_corners(&d).unwrap();
|
||||
assert!((c[0] - Vec3::new(-1.0, 0.5, 0.0)).length() < 1e-5 && (c[2] - Vec3::new(1.0, -0.5, 0.0)).length() < 1e-5);
|
||||
assert!(decal_axes(&Decal { normal: [0.0; 3], ..d }).is_none());
|
||||
assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pattern_varies() {
|
||||
for k in ProceduralKind::ALL {
|
||||
|
||||
@@ -275,7 +275,8 @@ fn nested_stack(f: &mut Fixture) -> Nested {
|
||||
);
|
||||
let mask = generator_mask(f, GeneratorKind::Position, None);
|
||||
let g1 = group(f, None, BlendMode::Normal, 0.8, Some(mask));
|
||||
let inner = put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None);
|
||||
let inner =
|
||||
put(f, 0, Some(g1), fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0)), (Channel::Metallic, Source::Uniform([0.3; 3]))]), None);
|
||||
let mut checker = Mask::new(MaskBackground::Black);
|
||||
checker.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.2, 1.0), projection: Projection::default() }));
|
||||
let g2 = group(f, Some(g1), BlendMode::Passthrough, 1.0, Some(checker));
|
||||
@@ -439,3 +440,125 @@ fn edits_off_the_hot_layer_invalidate_and_edits_to_it_do_not() {
|
||||
paint_rect(&mut f, n.top, (0, 0), (30, 30), 0.9);
|
||||
assert!(emptied(&f), "pixels above");
|
||||
}
|
||||
|
||||
/// Paint a half-covered rectangle (base color and roughness `v`) into a paint layer stored at
|
||||
/// `size` texels.
|
||||
fn paint_rect_at(f: &mut Fixture, id: LayerId, size: u32, (x0, y0): (u32, u32), (w, h): (u32, u32), v: f32) {
|
||||
for (ch, px) in [(Channel::BaseColor, vec![to_u16(v * 0.5), to_u16(0.1), 0, to_u16(0.5)]), (Channel::Roughness, vec![to_u16(v * 0.5), to_u16(0.5)])] {
|
||||
let img = f.pixels.layer_mut(id, ch, (size, size));
|
||||
for y in y0..y0 + h {
|
||||
for x in x0..x0 + w {
|
||||
img.set(x, y, &px);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_resample_sources_painted_at_another_resolution() {
|
||||
let mut f = fixture();
|
||||
let half = RES / 2;
|
||||
f.project.texture_sets[1].resolution = half;
|
||||
// The source lives in set B at half resolution, masked by half-resolution mask pixels.
|
||||
let src = add(&mut f, 1, LayerKind::Paint, None);
|
||||
paint_rect_at(&mut f, src, half, (20, 30), (60, 50), 0.9);
|
||||
let paint = effect(&mut f, EffectKind::Paint);
|
||||
let mask_id = paint.id;
|
||||
f.project.layer_mut(src).unwrap().mask = Some(Mask { effects: vec![paint], ..Mask::new(MaskBackground::Black) });
|
||||
let m = f.pixels.mask_mut(mask_id, (half, half));
|
||||
for y in 0..half {
|
||||
for x in 0..50 {
|
||||
m.set(x, y, &[to_u16(1.0), to_u16(1.0)]);
|
||||
}
|
||||
}
|
||||
add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Clouds, 0.0, 1.0))]), None);
|
||||
let inst = add(&mut f, 0, LayerKind::Instance { source: src }, None);
|
||||
let top = add(&mut f, 0, LayerKind::Paint, None);
|
||||
paint_rect(&mut f, top, (0, 0), (40, 40), 0.2);
|
||||
let out = reference(&f, 0);
|
||||
let rough = |x, y| out.value(Channel::Roughness, x, y)[0];
|
||||
// Painted roughness 0.9 at half coverage over the default 0.5, where the mask lets it through.
|
||||
assert!((rough(70, 120) - 0.7).abs() < 2e-3, "inside: {}", rough(70, 120));
|
||||
assert!((rough(180, 120) - 0.5).abs() < 2e-3, "masked out: {}", rough(180, 120));
|
||||
assert!((rough(70, 200) - 0.5).abs() < 2e-3, "not painted: {}", rough(70, 200));
|
||||
for hot in [top, inst] {
|
||||
check_cached(&f, 0, hot);
|
||||
}
|
||||
assert!(!check_cached(&f, 0, top).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
|
||||
let mut f = fixture();
|
||||
let low = add(&mut f, 0, fill(&[(Channel::Height, Source::Uniform([0.4; 3]))]), None);
|
||||
f.project.layer_mut(low).unwrap().channels.retain(|c, _| *c == Channel::Height);
|
||||
blend(&mut f, low, BlendMode::Normal, 0.5);
|
||||
let (mid, end) = (effect(&mut f, EffectKind::Anchor), effect(&mut f, EffectKind::Anchor));
|
||||
let (mid_id, end_id) = (mid.id, end.id);
|
||||
let mut raise = Fill::default();
|
||||
raise.sources.insert(Channel::Height, Source::Uniform([0.8; 3]));
|
||||
let raise = effect(&mut f, EffectKind::Material(raise));
|
||||
f.project.layer_mut(low).unwrap().content_effects.extend([mid, raise, end]);
|
||||
let top = add(&mut f, 0, LayerKind::Paint, None);
|
||||
paint_rect(&mut f, top, (0, 0), (60, 60), 0.3);
|
||||
// Without readers the stack is cached (anchors are still recorded) and exact.
|
||||
assert!(!check_cached(&f, 0, top).is_empty());
|
||||
// Readers: roughness reads the anchor inside the stack, metallic the one at its end.
|
||||
for (c, anchor) in [(Channel::Roughness, mid_id), (Channel::Metallic, end_id)] {
|
||||
let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height })]), None);
|
||||
f.project.layer_mut(reader).unwrap().channels.retain(|x, _| *x == c);
|
||||
}
|
||||
let out = reference(&f, 0);
|
||||
let at = |c| out.value(c, 128, 128)[0];
|
||||
// Half opacity over the default height 0: 0.4 before the raise, 0.8 after it.
|
||||
assert!((at(Channel::Roughness) - 0.2).abs() < 2e-3, "inside the stack: {}", at(Channel::Roughness));
|
||||
assert!((at(Channel::Metallic) - 0.4).abs() < 2e-3, "at the end: {}", at(Channel::Metallic));
|
||||
assert!((at(Channel::Height) - 0.4).abs() < 2e-3);
|
||||
assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything");
|
||||
// Behind a blur the cut reads the filtered field; before it, the unfiltered content.
|
||||
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 }));
|
||||
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
|
||||
let blurred = reference(&f, 0);
|
||||
assert!((blurred.value(Channel::Roughness, 128, 128)[0] - 0.2).abs() < 2e-3, "a flat height stays flat");
|
||||
let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
for t in all_tiles(RES, RES) {
|
||||
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
|
||||
}
|
||||
assert!(one_by_one == blurred);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gathering_filters_composite_identically_in_any_grouping_and_cached() {
|
||||
let mut f = fixture();
|
||||
let base = add(
|
||||
&mut f,
|
||||
0,
|
||||
fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9)), (Channel::Roughness, procedural(ProceduralKind::Checker, 0.0, 1.0))]),
|
||||
None,
|
||||
);
|
||||
let mut slope = Mask::new(MaskBackground::Black);
|
||||
slope.effects.push(effect(&mut f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
|
||||
slope.effects.push(effect(&mut f, EffectKind::Filter(Filter::SlopeBlur { radius: 24.0, scale: 3.0, seed: 1 })));
|
||||
let streaks = add(&mut f, 0, fill(&[(Channel::Metallic, procedural(ProceduralKind::Stripes, 0.0, 1.0))]), Some(slope));
|
||||
let top = add(&mut f, 0, LayerKind::Paint, None);
|
||||
paint_rect(&mut f, top, (30, 40), (150, 100), 0.4);
|
||||
let plain = reference(&f, 0);
|
||||
let warp = effect(&mut f, EffectKind::Filter(Filter::Warp { intensity: 30.0, scale: 4.0, seed: 3 }));
|
||||
f.project.layer_mut(base).unwrap().content_effects.push(warp);
|
||||
let line = effect(&mut f, EffectKind::Filter(Filter::DirectionalBlur { radius: 40.0, angle: 30.0 }));
|
||||
f.project.layer_mut(streaks).unwrap().content_effects.push(line);
|
||||
let want = reference(&f, 0);
|
||||
for c in [Channel::BaseColor, Channel::Roughness, Channel::Metallic] {
|
||||
assert!(want.channels[&c] != plain.channels[&c], "{c:?} changed by its filter");
|
||||
}
|
||||
let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
|
||||
let (images, baked) = (Default::default(), Default::default());
|
||||
for t in all_tiles(RES, RES) {
|
||||
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
|
||||
}
|
||||
assert!(one_by_one == want, "per-tile composites differ from one pass");
|
||||
for hot in [top, streaks] {
|
||||
assert!(!check_cached(&f, 0, hot).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,11 @@ pub enum Channel {
|
||||
AnisotropyAngle,
|
||||
/// Subsurface scattering weight (scatter color and radius are project shader settings).
|
||||
ScatterWeight,
|
||||
/// Transmission: how much of the dielectric base lets light through (refraction at the
|
||||
/// project's IOR, tinted by the base color) instead of reflecting it diffusely.
|
||||
Transmission,
|
||||
/// Tangent-space normal of the clear coat (relative to the mesh normal).
|
||||
CoatNormal,
|
||||
}
|
||||
|
||||
/// How a channel's values are stored and interpreted.
|
||||
@@ -50,7 +55,7 @@ pub enum ChannelKind {
|
||||
}
|
||||
|
||||
impl Channel {
|
||||
pub const ALL: [Channel; 19] = [
|
||||
pub const ALL: [Channel; 21] = [
|
||||
Channel::BaseColor,
|
||||
Channel::Metallic,
|
||||
Channel::Roughness,
|
||||
@@ -70,11 +75,14 @@ impl Channel {
|
||||
Channel::AnisotropyLevel,
|
||||
Channel::AnisotropyAngle,
|
||||
Channel::ScatterWeight,
|
||||
Channel::Transmission,
|
||||
Channel::CoatNormal,
|
||||
];
|
||||
|
||||
/// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering). Their
|
||||
/// defaults switch the lobes off, so a set without them shades exactly as before.
|
||||
pub const LOBES: [Channel; 8] = [
|
||||
/// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering,
|
||||
/// transmission). Their defaults switch the lobes off, so a set without them shades exactly
|
||||
/// as before.
|
||||
pub const LOBES: [Channel; 10] = [
|
||||
Channel::CoatWeight,
|
||||
Channel::CoatRoughness,
|
||||
Channel::SheenWeight,
|
||||
@@ -83,6 +91,8 @@ impl Channel {
|
||||
Channel::AnisotropyLevel,
|
||||
Channel::AnisotropyAngle,
|
||||
Channel::ScatterWeight,
|
||||
Channel::Transmission,
|
||||
Channel::CoatNormal,
|
||||
];
|
||||
|
||||
/// The channels of the default "PBR - Metallic Roughness" template.
|
||||
@@ -91,7 +101,7 @@ impl Channel {
|
||||
pub fn kind(self) -> ChannelKind {
|
||||
match self {
|
||||
Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => ChannelKind::Color,
|
||||
Channel::Normal => ChannelKind::NormalMap,
|
||||
Channel::Normal | Channel::CoatNormal => ChannelKind::NormalMap,
|
||||
Channel::Height => ChannelKind::Signed,
|
||||
_ => ChannelKind::Scalar,
|
||||
}
|
||||
@@ -110,12 +120,17 @@ impl Channel {
|
||||
match self {
|
||||
Channel::BaseColor => [0.5, 0.5, 0.5],
|
||||
Channel::Metallic | Channel::Height | Channel::Emissive => [0.0; 3],
|
||||
Channel::CoatWeight | Channel::SheenWeight | Channel::AnisotropyLevel | Channel::AnisotropyAngle | Channel::ScatterWeight => [0.0; 3],
|
||||
Channel::CoatWeight
|
||||
| Channel::SheenWeight
|
||||
| Channel::AnisotropyLevel
|
||||
| Channel::AnisotropyAngle
|
||||
| Channel::ScatterWeight
|
||||
| Channel::Transmission => [0.0; 3],
|
||||
Channel::CoatRoughness => [0.1; 3],
|
||||
Channel::SheenColor => [1.0; 3],
|
||||
Channel::SheenRoughness => [0.5; 3],
|
||||
Channel::Roughness => [0.5; 3],
|
||||
Channel::Normal => [0.5, 0.5, 1.0],
|
||||
Channel::Normal | Channel::CoatNormal => [0.5, 0.5, 1.0],
|
||||
Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3],
|
||||
Channel::SpecularLevel | Channel::Glossiness => [0.5; 3],
|
||||
// F0 of a common dielectric (4 %).
|
||||
@@ -144,6 +159,8 @@ impl Channel {
|
||||
Channel::AnisotropyLevel => "Anisotropy level",
|
||||
Channel::AnisotropyAngle => "Anisotropy angle",
|
||||
Channel::ScatterWeight => "Scattering weight",
|
||||
Channel::Transmission => "Transmission",
|
||||
Channel::CoatNormal => "Coat normal",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +186,8 @@ impl Channel {
|
||||
Channel::AnisotropyLevel => "aniso",
|
||||
Channel::AnisotropyAngle => "aniso angle",
|
||||
Channel::ScatterWeight => "scatter",
|
||||
Channel::Transmission => "transm",
|
||||
Channel::CoatNormal => "coat nrm",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,6 +213,8 @@ impl Channel {
|
||||
Channel::AnisotropyLevel => "anisotropyLevel",
|
||||
Channel::AnisotropyAngle => "anisotropyAngle",
|
||||
Channel::ScatterWeight => "scatterWeight",
|
||||
Channel::Transmission => "transmission",
|
||||
Channel::CoatNormal => "coatNormal",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,7 +295,9 @@ mod tests {
|
||||
}
|
||||
for c in Channel::LOBES {
|
||||
assert!(Channel::ALL.contains(&c));
|
||||
let off = matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness) || c.default_value() == [0.0; 3];
|
||||
// Tints, roughnesses and the flat coat normal only matter once their lobe has weight.
|
||||
let off =
|
||||
matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness | Channel::CoatNormal) || c.default_value() == [0.0; 3];
|
||||
assert!(off, "{c:?} must default to an inactive lobe");
|
||||
}
|
||||
assert_eq!(Channel::parse("sheen color"), Some(Channel::SheenColor));
|
||||
|
||||
+179
-2
@@ -4,7 +4,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BlendMode, Channel};
|
||||
use crate::{BlendMode, Channel, ChannelKind, lum};
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
@@ -152,6 +152,28 @@ pub enum Projection {
|
||||
Spherical { scale: f32 },
|
||||
/// Cylindrical projection around an axis.
|
||||
Cylindrical { scale: f32, axis: u8 },
|
||||
/// A geometry decal: the image projected from a frame placed on the surface (outside the
|
||||
/// frame, behind it or beyond its depth the fill does not cover).
|
||||
Decal(Decal),
|
||||
}
|
||||
|
||||
/// The frame a decal projects from (world space).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Decal {
|
||||
/// The surface point the decal was placed on.
|
||||
pub center: [f32; 3],
|
||||
/// The surface normal there: the decal projects along it.
|
||||
pub normal: [f32; 3],
|
||||
/// Up direction of the unrotated frame.
|
||||
pub up: [f32; 3],
|
||||
/// Width and height (world units).
|
||||
pub size: [f32; 2],
|
||||
/// Rotation around the normal (degrees).
|
||||
pub rotation: f32,
|
||||
/// Shift of the frame from `center` along the unrotated right and up directions (world units).
|
||||
pub offset: [f32; 2],
|
||||
/// How far in front of and behind the frame the decal reaches (world units).
|
||||
pub depth: f32,
|
||||
}
|
||||
|
||||
impl Default for Projection {
|
||||
@@ -168,6 +190,7 @@ impl Projection {
|
||||
Projection::Planar { .. } => "Planar projection",
|
||||
Projection::Spherical { .. } => "Spherical projection",
|
||||
Projection::Cylindrical { .. } => "Cylindrical projection",
|
||||
Projection::Decal(_) => "Decal projection",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -480,6 +503,49 @@ pub enum Filter {
|
||||
saturation: f32,
|
||||
lightness: f32,
|
||||
},
|
||||
/// Contrast around mid gray and a luminosity shift, both −1..1 (0 = unchanged).
|
||||
ContrastLuminosity {
|
||||
contrast: f32,
|
||||
luminosity: f32,
|
||||
},
|
||||
/// Color offsets (−1..1 per component) weighted towards the shadows, midtones and highlights.
|
||||
ColorBalance {
|
||||
shadows: [f32; 3],
|
||||
midtones: [f32; 3],
|
||||
highlights: [f32; 3],
|
||||
},
|
||||
/// Luminance mapped through evenly spaced colors (linear RGB; scalars read their gray).
|
||||
GradientMap {
|
||||
colors: Vec<[f32; 3]>,
|
||||
},
|
||||
/// Quantize to `levels` steps (2..64).
|
||||
Posterize {
|
||||
levels: f32,
|
||||
},
|
||||
/// Keep values within `min..max`.
|
||||
Clamp {
|
||||
min: f32,
|
||||
max: f32,
|
||||
},
|
||||
/// Shift each texel's lookup along a noise vector field: `intensity` in texels at 2K,
|
||||
/// `scale` noise features per UV unit.
|
||||
Warp {
|
||||
intensity: f32,
|
||||
scale: f32,
|
||||
seed: u32,
|
||||
},
|
||||
/// Blur along one direction: `radius` in texels at 2K, `angle` in degrees.
|
||||
DirectionalBlur {
|
||||
radius: f32,
|
||||
angle: f32,
|
||||
},
|
||||
/// Smear values downhill along a noise height field ("slope blur"): `radius` in texels at
|
||||
/// 2K, `scale` noise features per UV unit.
|
||||
SlopeBlur {
|
||||
radius: f32,
|
||||
scale: f32,
|
||||
seed: u32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1.
|
||||
@@ -530,7 +596,83 @@ pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [
|
||||
[hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)]
|
||||
}
|
||||
|
||||
/// Apply a 0..1 function to each component of a channel value: signed values map through
|
||||
/// 0..1, normals are left alone.
|
||||
pub fn per_unit(kind: ChannelKind, v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] {
|
||||
match kind {
|
||||
ChannelKind::NormalMap => v,
|
||||
// One-component channels hold their value in the first slot (read as gray).
|
||||
ChannelKind::Signed => [f(v[0] * 0.5 + 0.5) * 2.0 - 1.0; 3],
|
||||
ChannelKind::Scalar => [f(v[0]); 3],
|
||||
ChannelKind::Color => v.map(f),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color at `t` (0..1) of a gradient through evenly spaced `colors` (None when empty).
|
||||
pub fn gradient(colors: &[[f32; 3]], t: f32) -> Option<[f32; 3]> {
|
||||
let last = colors.len().checked_sub(1)?;
|
||||
let pos = if t.is_finite() { t.clamp(0.0, 1.0) * last as f32 } else { 0.0 };
|
||||
let i = (pos.floor() as usize).min(last);
|
||||
let (a, b) = (colors.get(i)?, colors.get((i + 1).min(last))?);
|
||||
let f = pos - i as f32;
|
||||
Some(std::array::from_fn(|k| a[k] + (b[k] - a[k]) * f))
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
/// Whether the filter reads neighbouring texels (the compositor runs it over a region).
|
||||
pub fn is_neighbourhood(&self) -> bool {
|
||||
matches!(self, Filter::Blur { .. } | Filter::Sharpen { .. } | Filter::Warp { .. } | Filter::DirectionalBlur { .. } | Filter::SlopeBlur { .. })
|
||||
}
|
||||
|
||||
/// The filter applied to one value of a channel of `kind` (masks are scalars). None for
|
||||
/// neighbourhood filters and where it changes nothing (an empty gradient).
|
||||
pub fn point(&self, kind: ChannelKind, v: [f32; 3]) -> Option<[f32; 3]> {
|
||||
let unit = |x: f32| if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.0 };
|
||||
Some(match self {
|
||||
Filter::Invert => per_unit(kind, v, |x| 1.0 - x),
|
||||
Filter::Threshold { level } => per_unit(kind, v, |x| if x >= *level { 1.0 } else { 0.0 }),
|
||||
Filter::Hsl { hue, saturation, lightness } => match kind {
|
||||
ChannelKind::Color => hsl_adjust(v, *hue, *saturation, *lightness),
|
||||
_ => per_unit(kind, v, |x| hsl_adjust([x; 3], 0.0, 0.0, *lightness)[0]),
|
||||
},
|
||||
Filter::ContrastLuminosity { contrast, luminosity } => {
|
||||
let k = 1.0 + contrast.clamp(-1.0, 1.0);
|
||||
per_unit(kind, v, |x| unit((x - 0.5) * k + 0.5 + luminosity))
|
||||
}
|
||||
Filter::ColorBalance { shadows, midtones, highlights } => {
|
||||
// Smooth weights summing to 1: shadows fade out and highlights in with lightness.
|
||||
let weights = |l: f32| {
|
||||
let l = unit(l);
|
||||
((1.0 - l) * (1.0 - l), 2.0 * l * (1.0 - l), l * l)
|
||||
};
|
||||
let shift = |k: usize, l: f32| {
|
||||
let (s, m, h) = weights(l);
|
||||
shadows.get(k).copied().unwrap_or(0.0) * s + midtones.get(k).copied().unwrap_or(0.0) * m + highlights.get(k).copied().unwrap_or(0.0) * h
|
||||
};
|
||||
match kind {
|
||||
ChannelKind::Color => {
|
||||
let l = lum(v);
|
||||
std::array::from_fn(|k| unit(v[k] + shift(k, l)))
|
||||
}
|
||||
_ => per_unit(kind, v, |x| unit(x + (shift(0, x) + shift(1, x) + shift(2, x)) / 3.0)),
|
||||
}
|
||||
}
|
||||
Filter::GradientMap { colors } => match kind {
|
||||
ChannelKind::Color => gradient(colors, lum(v))?,
|
||||
_ => per_unit(kind, v, |x| gradient(colors, x).map_or(x, lum)),
|
||||
},
|
||||
Filter::Posterize { levels } => {
|
||||
let steps = (levels.clamp(2.0, 64.0).round() - 1.0).max(1.0);
|
||||
per_unit(kind, v, |x| (unit(x) * steps).round() / steps)
|
||||
}
|
||||
Filter::Clamp { min, max } => {
|
||||
let (lo, hi) = (min.min(*max), min.max(*max));
|
||||
per_unit(kind, v, |x| x.max(lo).min(hi))
|
||||
}
|
||||
Filter::Blur { .. } | Filter::Sharpen { .. } | Filter::Warp { .. } | Filter::DirectionalBlur { .. } | Filter::SlopeBlur { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
Filter::Blur { .. } => "Blur",
|
||||
@@ -538,6 +680,14 @@ impl Filter {
|
||||
Filter::Invert => "Invert",
|
||||
Filter::Threshold { .. } => "Threshold",
|
||||
Filter::Hsl { .. } => "HSL Perceptive",
|
||||
Filter::ContrastLuminosity { .. } => "Contrast/Luminosity",
|
||||
Filter::ColorBalance { .. } => "Color Balance",
|
||||
Filter::GradientMap { .. } => "Gradient Map",
|
||||
Filter::Posterize { .. } => "Posterize",
|
||||
Filter::Clamp { .. } => "Clamp",
|
||||
Filter::Warp { .. } => "Warp",
|
||||
Filter::DirectionalBlur { .. } => "Blur Directional",
|
||||
Filter::SlopeBlur { .. } => "Slope Blur",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -675,6 +825,30 @@ mod tests {
|
||||
assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_filters_map_values_and_skip_neighbourhood_filters() {
|
||||
let c = ChannelKind::Color;
|
||||
let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4);
|
||||
let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 };
|
||||
assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0]));
|
||||
assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3]));
|
||||
let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] };
|
||||
assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0]));
|
||||
assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0]));
|
||||
assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing");
|
||||
assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0]));
|
||||
assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic");
|
||||
let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] };
|
||||
assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99);
|
||||
assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3]));
|
||||
assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0]));
|
||||
for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] {
|
||||
assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none());
|
||||
}
|
||||
let nan = Filter::ContrastLuminosity { contrast: f32::NAN, luminosity: f32::NAN };
|
||||
assert!(nan.point(c, [0.5; 3]).unwrap().iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_targets_and_anchor_reads() {
|
||||
assert_eq!(EffectKind::Anchor.content_only(), Some(true));
|
||||
@@ -683,7 +857,10 @@ mod tests {
|
||||
let mut l = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]);
|
||||
assert!(!l.reads_anchor());
|
||||
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height };
|
||||
l.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) });
|
||||
l.mask = Some(Mask {
|
||||
effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })],
|
||||
..Mask::new(MaskBackground::Black)
|
||||
});
|
||||
assert!(l.reads_anchor());
|
||||
}
|
||||
|
||||
|
||||
@@ -15,10 +15,10 @@ pub mod project;
|
||||
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
|
||||
pub use channel::{Channel, ChannelFormat, ChannelKind};
|
||||
pub use layer::{
|
||||
ChannelBlend, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, MaskBackground, Procedural,
|
||||
ProceduralKind, Projection, Source, hsl_adjust,
|
||||
ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, MaskBackground,
|
||||
Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit,
|
||||
};
|
||||
pub use project::{AoMixing, BakeMatch, BakeSettings, BakedMap, DisplaySettings, FORMAT_VERSION, NormalFormat, NormalMixing, Project, TextureSet, TileGrid, ToneMapping, UDIM_RANGE};
|
||||
pub use project::{AoMixing, BakeMatch, BakeSettings, BakedMap, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, NormalFormat, NormalMixing, Project, TextureSet, TileGrid, ToneMapping, UDIM_RANGE};
|
||||
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
|
||||
pub enum CoreError {
|
||||
|
||||
@@ -379,6 +379,52 @@ pub struct DisplaySettings {
|
||||
pub scatter_color: [f32; 3],
|
||||
/// Subsurface scattering mean free path as a fraction of the mesh's bounding radius.
|
||||
pub scatter_radius: f32,
|
||||
/// Index of refraction of transmissive surfaces (where the Transmission channel is painted).
|
||||
pub ior: f32,
|
||||
/// Depth of field of the viewport and the path tracer (thin lens).
|
||||
pub dof: DepthOfField,
|
||||
}
|
||||
|
||||
/// A thin-lens camera's depth of field (Painter's Display settings: focus distance and aperture).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DepthOfField {
|
||||
pub enabled: bool,
|
||||
/// Distance of the plane in focus along the view axis (world units); 0 focuses on the
|
||||
/// camera's orbit target.
|
||||
pub focus_distance: f32,
|
||||
/// Lens radius as a fraction of the mesh's bounding radius: how fast the blur grows away
|
||||
/// from the focus plane.
|
||||
pub aperture: f32,
|
||||
}
|
||||
|
||||
impl Default for DepthOfField {
|
||||
fn default() -> Self {
|
||||
DepthOfField { enabled: false, focus_distance: 0.0, aperture: 0.05 }
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved viewpoint of the camera list (the default camera's orbit parameters, as in
|
||||
/// `geom::OrbitCamera`): saved views and cameras imported with the mesh.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Camera {
|
||||
pub name: String,
|
||||
pub target: [f32; 3],
|
||||
/// Radians around +Y.
|
||||
pub yaw: f32,
|
||||
/// Radians above the horizon.
|
||||
pub pitch: f32,
|
||||
pub distance: f32,
|
||||
/// Vertical field of view, degrees (orthographic: the view height at `distance`).
|
||||
pub fov: f32,
|
||||
pub ortho: bool,
|
||||
}
|
||||
|
||||
impl Default for Camera {
|
||||
fn default() -> Self {
|
||||
Camera { name: "Camera".into(), target: [0.0; 3], yaw: 0.0, pitch: 0.0, distance: 5.0, fov: 40.0, ortho: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefix of [`DisplaySettings::environment`] naming an image resource.
|
||||
@@ -413,6 +459,8 @@ impl Default for DisplaySettings {
|
||||
parallax: false,
|
||||
scatter_color: [1.0, 0.4, 0.25],
|
||||
scatter_radius: 0.1,
|
||||
ior: 1.5,
|
||||
dof: DepthOfField::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -428,6 +476,9 @@ pub struct Project {
|
||||
pub layers: BTreeMap<LayerId, Layer>,
|
||||
pub next_id: u64,
|
||||
pub display: DisplaySettings,
|
||||
/// Saved and imported cameras (the viewport's default camera is not in the list).
|
||||
#[serde(default)]
|
||||
pub cameras: Vec<Camera>,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
@@ -441,6 +492,7 @@ impl Project {
|
||||
layers: BTreeMap::new(),
|
||||
next_id: 1,
|
||||
display: DisplaySettings::default(),
|
||||
cameras: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! The camera list (Painter's viewport camera menu: the default camera plus saved and imported
|
||||
//! cameras, saved with the project) and the depth of field focus pick.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::Camera;
|
||||
use texturecraft_geom::OrbitCamera;
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, f32p, strp, u64p};
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Name of the viewport's own camera in the camera menu (it is not in the list).
|
||||
pub const DEFAULT_CAMERA: &str = "Default camera";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("camera.list", "Cameras", [], None, "{}", always, |s, _| Ok(list(s))),
|
||||
cmd!("camera.add", "Save view as camera", [], None, "{name?}", always, add),
|
||||
cmd!(
|
||||
"camera.select",
|
||||
"Select camera",
|
||||
[],
|
||||
None,
|
||||
"{index? | name?} (neither, or name \"Default camera\": the default camera framing the mesh)",
|
||||
always,
|
||||
select
|
||||
),
|
||||
cmd!("camera.remove", "Remove camera", [], None, "{index? | name?}", has_cameras, remove),
|
||||
cmd!("camera.rename", "Rename camera", [], None, "{index? | name?, to}", has_cameras, rename),
|
||||
cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at),
|
||||
]
|
||||
}
|
||||
|
||||
fn has_cameras(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.doc.project.cameras.is_empty() { Err("the project has no saved cameras".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The view as a saved camera.
|
||||
fn saved(c: &OrbitCamera, name: String) -> Camera {
|
||||
Camera { name, target: c.target.to_array(), yaw: c.yaw, pitch: c.pitch, distance: c.distance, fov: c.fov, ortho: c.ortho }
|
||||
}
|
||||
|
||||
/// Move the view to saved camera `c` (values from project files are checked and clamped).
|
||||
fn apply(view: &mut OrbitCamera, c: &Camera) {
|
||||
let target = Vec3::from(c.target);
|
||||
if target.is_finite() {
|
||||
view.target = target;
|
||||
}
|
||||
let r = view.scene_radius.max(1e-3);
|
||||
let ok = |v: f32| v.is_finite().then_some(v);
|
||||
view.yaw = ok(c.yaw).unwrap_or(view.yaw);
|
||||
view.pitch = ok(c.pitch).map_or(view.pitch, |p| p.clamp(-89f32.to_radians(), 89f32.to_radians()));
|
||||
view.distance = ok(c.distance).map_or(view.distance, |d| d.clamp(r * 0.05, r * 200.0));
|
||||
view.fov = ok(c.fov).map_or(view.fov, |f| f.clamp(5.0, 150.0));
|
||||
view.ortho = c.ortho;
|
||||
}
|
||||
|
||||
/// The saved camera the view is at, if any.
|
||||
pub fn current(s: &Session) -> Option<usize> {
|
||||
let mut view = s.camera;
|
||||
s.doc.project.cameras.iter().position(|c| {
|
||||
apply(&mut view, c);
|
||||
let close = |a: f32, b: f32| (a - b).abs() <= 1e-4 * (1.0 + a.abs());
|
||||
(view.target - s.camera.target).length() <= 1e-4 * (1.0 + view.distance)
|
||||
&& close(view.yaw, s.camera.yaw)
|
||||
&& close(view.pitch, s.camera.pitch)
|
||||
&& close(view.distance, s.camera.distance)
|
||||
&& close(view.fov, s.camera.fov)
|
||||
&& view.ortho == s.camera.ortho
|
||||
})
|
||||
}
|
||||
|
||||
fn list(s: &Session) -> Value {
|
||||
let cams: Vec<Value> = s
|
||||
.doc
|
||||
.project
|
||||
.cameras
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
json!({
|
||||
"index": i, "name": c.name, "fov": c.fov, "ortho": c.ortho, "distance": c.distance,
|
||||
"yaw": c.yaw.to_degrees(), "pitch": c.pitch.to_degrees(), "target": c.target,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
json!({ "cameras": cams, "current": current(s) })
|
||||
}
|
||||
|
||||
/// The camera `index` or `name` of params `p` points at.
|
||||
fn which(s: &Session, cmd: &str, p: &Value) -> Result<usize> {
|
||||
let cams = &s.doc.project.cameras;
|
||||
let found = match (u64p(p, "index"), strp(p, "name")) {
|
||||
(Some(i), _) => usize::try_from(i).ok().filter(|i| *i < cams.len()),
|
||||
(None, Some(n)) => cams.iter().position(|c| c.name == n),
|
||||
(None, None) => return Err(bad(cmd, "give `index` or `name`")),
|
||||
};
|
||||
found.ok_or_else(|| bad(cmd, "no such camera (see camera.list)"))
|
||||
}
|
||||
|
||||
fn unique_name(s: &Session, base: &str) -> String {
|
||||
let taken = |n: &str| n == DEFAULT_CAMERA || s.doc.project.cameras.iter().any(|c| c.name == n);
|
||||
if !taken(base) {
|
||||
return base.to_string();
|
||||
}
|
||||
(2..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let base = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Camera");
|
||||
let name = unique_name(s, base);
|
||||
let cam = saved(&s.camera, name.clone());
|
||||
s.edit("Save camera", |s| {
|
||||
s.doc.project.cameras.push(cam);
|
||||
Ok(json!({ "index": s.doc.project.cameras.len() - 1, "name": name }))
|
||||
})
|
||||
}
|
||||
|
||||
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.camera.fov = s.doc.project.display.fov;
|
||||
s.camera.ortho = false;
|
||||
return crate::execute(s, "viewport.frame", &Value::Null);
|
||||
}
|
||||
let i = which(s, "camera.select", p)?;
|
||||
if let Some(c) = s.doc.project.cameras.get(i).cloned() {
|
||||
apply(&mut s.camera, &c);
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(crate::view_cmds::camera_json(s))
|
||||
}
|
||||
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = which(s, "camera.remove", p)?;
|
||||
s.edit("Remove camera", |s| {
|
||||
let c = s.doc.project.cameras.remove(i);
|
||||
Ok(json!({ "removed": c.name }))
|
||||
})
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = which(s, "camera.rename", p)?;
|
||||
let to = strp(p, "to").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("camera.rename", "`to` (the new name) is required"))?;
|
||||
if s.doc.project.cameras.get(i).is_some_and(|c| c.name == to) {
|
||||
return Ok(json!({ "index": i, "name": to }));
|
||||
}
|
||||
let name = unique_name(s, to);
|
||||
s.edit("Rename camera", |s| {
|
||||
if let Some(c) = s.doc.project.cameras.get_mut(i) {
|
||||
c.name = name.clone();
|
||||
}
|
||||
Ok(json!({ "index": i, "name": name }))
|
||||
})
|
||||
}
|
||||
|
||||
/// Focus the depth of field on the mesh under viewport pixel (x, y).
|
||||
fn focus_at(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("viewport.focusAt", "`x` and `y` (viewport pixels) are required")) };
|
||||
let vp = viewport_of(s, p);
|
||||
let hit = s.pick(Vec2::new(x, y), vp).ok_or_else(|| bad("viewport.focusAt", "no mesh under that point"))?;
|
||||
let depth = (hit.pos - s.camera.eye()).dot(s.camera.forward()).max(1e-4);
|
||||
s.doc.project.display.dof.focus_distance = depth;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "focusDistance": depth }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::execute;
|
||||
|
||||
fn session() -> Session {
|
||||
Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:sphere", None, 128).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cameras_add_select_rename_remove_and_undo() {
|
||||
let mut s = session();
|
||||
let home = s.camera;
|
||||
assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], Value::Null);
|
||||
execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "fov": 25, "ortho": true})).unwrap();
|
||||
let side = s.camera;
|
||||
assert_eq!(execute(&mut s, "camera.add", &json!({"name": "Side"})).unwrap()["index"], 0);
|
||||
assert_eq!(execute(&mut s, "camera.add", &json!({"name": "Side"})).unwrap()["name"], "Side 2", "names stay unique");
|
||||
assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], 0);
|
||||
execute(&mut s, "camera.select", &json!({})).unwrap();
|
||||
assert!(!s.camera.ortho && s.camera.fov == s.doc.project.display.fov, "the default camera");
|
||||
assert_eq!((s.camera.yaw, s.camera.target), (side.yaw, home.target), "framing the mesh, keeping the angles");
|
||||
execute(&mut s, "camera.orbit", &json!({"dx": 40})).unwrap();
|
||||
execute(&mut s, "camera.select", &json!({"name": "Side"})).unwrap();
|
||||
assert_eq!(s.camera, side, "selecting brings back the saved view, fov and projection");
|
||||
execute(&mut s, "camera.rename", &json!({"index": 1, "to": "Top"})).unwrap();
|
||||
execute(&mut s, "camera.remove", &json!({"name": "Side"})).unwrap();
|
||||
let list = execute(&mut s, "camera.list", &Value::Null).unwrap();
|
||||
assert_eq!(list["cameras"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(list["cameras"][0]["name"], "Top");
|
||||
assert!(execute(&mut s, "camera.select", &json!({"index": 5})).is_err());
|
||||
assert!(execute(&mut s, "camera.rename", &json!({"index": 0})).is_err(), "`to` is required");
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cameras_round_trip_through_the_project_file() {
|
||||
let mut s = session();
|
||||
execute(&mut s, "camera.set", &json!({"yaw": -20, "fov": 60})).unwrap();
|
||||
execute(&mut s, "camera.add", &json!({"name": "Hero"})).unwrap();
|
||||
execute(&mut s, "display.set", &json!({"dof": {"enabled": true, "focusDistance": 3.5, "aperture": 0.2}, "ior": 1.33})).unwrap();
|
||||
let bytes = texturecraft_formats::save_project_bytes(&s.project_file()).unwrap();
|
||||
let back = Session::from_project_bytes(&bytes).unwrap();
|
||||
assert_eq!(back.doc.project.cameras, s.doc.project.cameras);
|
||||
assert_eq!(back.doc.project.display.dof, s.doc.project.display.dof);
|
||||
assert_eq!(back.doc.project.display.ior, 1.33);
|
||||
// Projects saved before cameras and depth of field existed load with the defaults.
|
||||
let mut v = serde_json::to_value(&s.doc.project).unwrap();
|
||||
v.as_object_mut().unwrap().remove("cameras");
|
||||
v["display"].as_object_mut().unwrap().remove("dof");
|
||||
let old: texturecraft_core::Project = serde_json::from_value(v).unwrap();
|
||||
assert!(old.cameras.is_empty() && !old.display.dof.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_at_picks_the_depth_under_the_cursor() {
|
||||
let mut s = session();
|
||||
let vp = s.viewport;
|
||||
let r = execute(&mut s, "viewport.focusAt", &json!({"x": vp.x / 2.0, "y": vp.y / 2.0})).unwrap();
|
||||
let d = r["focusDistance"].as_f64().unwrap() as f32;
|
||||
// The front of the unit sphere, one radius before the orbit target.
|
||||
assert!((d - (s.camera.distance - 1.0)).abs() < 0.05, "{d} vs {}", s.camera.distance);
|
||||
assert_eq!(s.doc.project.display.dof.focus_distance, d);
|
||||
assert!(execute(&mut s, "viewport.focusAt", &json!({"x": 1, "y": 1})).is_err(), "nothing under the corner");
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::tool_cmds::specs());
|
||||
v.extend(crate::path_tool::specs());
|
||||
v.extend(crate::view_cmds::specs());
|
||||
v.extend(crate::camera_cmds::specs());
|
||||
v.extend(crate::quick_mask::specs());
|
||||
v.extend(crate::set_cmds::specs());
|
||||
v.extend(crate::project_cmds::specs());
|
||||
@@ -68,6 +69,8 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::resource_cmds::specs());
|
||||
v.extend(crate::material_lib::specs());
|
||||
v.extend(crate::smart_masks::specs());
|
||||
v.extend(crate::filter_lib::specs());
|
||||
v.extend(crate::decal_cmds::specs());
|
||||
v
|
||||
})
|
||||
}
|
||||
@@ -159,7 +162,12 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Blen
|
||||
|
||||
/// A color: `[r, g, b]` (linear 0..1) or `"#rrggbb"` (sRGB hex, converted to linear).
|
||||
pub(crate) fn color_param(p: &Value, key: &str) -> Option<[f32; 3]> {
|
||||
match p.get(key)? {
|
||||
color_of(p.get(key)?)
|
||||
}
|
||||
|
||||
/// A color value (see [`color_param`]).
|
||||
pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> {
|
||||
match v {
|
||||
Value::Array(a) if a.len() >= 3 => {
|
||||
let v: Vec<f32> = a.iter().take(3).map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
|
||||
if v.iter().all(|x| x.is_finite()) { Some([v[0], v[1], v[2]]) } else { None }
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Geometry decals: an image resource projected onto the surface from a frame placed on it
|
||||
//! (Painter's decal fill with a planar projection), as a fill layer with a decal projection.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp};
|
||||
use crate::tool_cmds::viewport_of;
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"layer.add.decal",
|
||||
"Add decal",
|
||||
[],
|
||||
None,
|
||||
"{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface",
|
||||
always,
|
||||
add
|
||||
),
|
||||
cmd!(
|
||||
"layer.decal.set",
|
||||
"Edit decal",
|
||||
[],
|
||||
None,
|
||||
"{layer?, x?, y?, viewport? | position?, normal? (re-place it), size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// A `[x, y, z]` param of finite numbers.
|
||||
fn vec3(p: &Value, key: &str) -> Option<Vec3> {
|
||||
let a = p.get(key)?.as_array()?;
|
||||
let v: Vec<f32> = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
|
||||
match v.as_slice() {
|
||||
[x, y, z] => Some(Vec3::new(*x, *y, *z)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view
|
||||
/// center by default) or `position` + `normal`. None when `optional` and neither is given.
|
||||
fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result<Option<(Vec3, Vec3)>> {
|
||||
if let Some(pos) = vec3(p, "position") {
|
||||
let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?;
|
||||
return Ok(Some((pos, n)));
|
||||
}
|
||||
let vp = viewport_of(s, p);
|
||||
let at = match (f32p(p, "x"), f32p(p, "y")) {
|
||||
(Some(x), Some(y)) => Vec2::new(x, y),
|
||||
_ if optional => return Ok(None),
|
||||
_ => vp * 0.5,
|
||||
};
|
||||
let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?;
|
||||
if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) {
|
||||
return Err(bad(cmd, "that surface belongs to another texture set"));
|
||||
}
|
||||
Ok(Some((hit.pos, hit.nrm)))
|
||||
}
|
||||
|
||||
/// The mesh's diagonal (decal sizes are relative to it).
|
||||
fn mesh_size(s: &Session) -> f32 {
|
||||
let (lo, hi) = s.mesh.bounds();
|
||||
(hi - lo).length().max(1e-3)
|
||||
}
|
||||
|
||||
/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`).
|
||||
fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> {
|
||||
let v = p.get("size")?;
|
||||
let size = match v.as_array() {
|
||||
Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32],
|
||||
None => {
|
||||
let h = v.as_f64()? as f32;
|
||||
[h * aspect, h]
|
||||
}
|
||||
};
|
||||
size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0)))
|
||||
}
|
||||
|
||||
/// The camera's up direction (decals are placed upright on screen).
|
||||
fn screen_up(s: &Session) -> Vec3 {
|
||||
s.camera.view().inverse().transform_vector3(Vec3::Y)
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "layer.add.decal";
|
||||
let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string();
|
||||
let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?;
|
||||
let aspect = img.width as f32 / img.height.max(1) as f32;
|
||||
let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?;
|
||||
let diag = mesh_size(s);
|
||||
let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]);
|
||||
let decal = Decal {
|
||||
center: center.to_array(),
|
||||
normal: normal.to_array(),
|
||||
up: screen_up(s).to_array(),
|
||||
size,
|
||||
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
|
||||
offset: [0.0; 2],
|
||||
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)),
|
||||
};
|
||||
let ts = s.ts();
|
||||
let base =
|
||||
strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string());
|
||||
let name = s.doc.project.next_layer_name(ts, &base);
|
||||
let id = s.edit("Add decal", |s| {
|
||||
let id = s.doc.project.alloc_id();
|
||||
let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() };
|
||||
fill.sources.insert(Channel::BaseColor, Source::Image { name: image.clone() });
|
||||
crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor]))
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0, "decal": decal }))
|
||||
}
|
||||
|
||||
/// The decal of fill layer `id`.
|
||||
fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result<Decal> {
|
||||
match &s.doc.project.layer(id)?.kind {
|
||||
LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d),
|
||||
_ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")),
|
||||
}
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "layer.decal.set";
|
||||
let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?;
|
||||
let mut d = decal_of(s, cmd, id)?;
|
||||
let diag = mesh_size(s);
|
||||
if let Some((center, normal)) = placement(s, cmd, p, true)? {
|
||||
(d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
|
||||
}
|
||||
if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) {
|
||||
d.size = size;
|
||||
}
|
||||
if let Some(r) = f32p(p, "rotation") {
|
||||
d.rotation = r.rem_euclid(360.0);
|
||||
}
|
||||
if let Some(o) = p.get("offset").and_then(Value::as_array) {
|
||||
let v: Vec<f32> = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
|
||||
let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) };
|
||||
d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)];
|
||||
}
|
||||
if let Some(v) = f32p(p, "depth") {
|
||||
d.depth = v.clamp(diag * 1e-4, diag * 10.0);
|
||||
}
|
||||
let image = strp(p, "image").map(str::to_string);
|
||||
if let Some(name) = &image
|
||||
&& !s.doc.resources.contains_key(name)
|
||||
{
|
||||
return Err(bad(cmd, format!("no image resource `{name}`")));
|
||||
}
|
||||
s.edit("Edit decal", |s| {
|
||||
if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind {
|
||||
f.projection = Projection::Decal(d);
|
||||
if let Some(name) = image {
|
||||
f.sources.insert(Channel::BaseColor, Source::Image { name });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0, "decal": d }))
|
||||
}
|
||||
@@ -114,6 +114,7 @@ impl Session {
|
||||
let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?;
|
||||
let ext = ext_of(file_name);
|
||||
let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?;
|
||||
s.doc.project.cameras = imported.cameras;
|
||||
s.log.extend(imported.report.warnings.iter().cloned());
|
||||
s.log.push(format!(
|
||||
"Imported {} ({} triangles, {} materials{})",
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The filter library (Painter's Filters shelf): adjustment, blur and distortion filters for
|
||||
//! layer content and masks, and material finishes (content only). `effect.add.filter` adds one
|
||||
//! by id; `filter.list` lists them with their default parameters.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Channel, EffectKind, Fill, Filter, Levels, Procedural, ProceduralKind, Projection, Source};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, color_of, color_param, f32p, u64p};
|
||||
use crate::{Result, cmd};
|
||||
|
||||
/// A filter of the library.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FilterDef {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
/// Shelf group.
|
||||
pub group: &'static str,
|
||||
/// Usable on masks too (material finishes only fill layer content).
|
||||
pub mask: bool,
|
||||
}
|
||||
|
||||
const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef {
|
||||
FilterDef { id, label, group, mask }
|
||||
}
|
||||
|
||||
pub const FILTERS: &[FilterDef] = &[
|
||||
def("hsl", "HSL Perceptive", "Adjustments", true),
|
||||
def("levels", "Levels", "Adjustments", true),
|
||||
def("contrastLuminosity", "Contrast/Luminosity", "Adjustments", true),
|
||||
def("colorBalance", "Color Balance", "Adjustments", true),
|
||||
def("gradientMap", "Gradient Map", "Adjustments", true),
|
||||
def("posterize", "Posterize", "Adjustments", true),
|
||||
def("clamp", "Clamp", "Adjustments", true),
|
||||
def("invert", "Invert", "Adjustments", true),
|
||||
def("threshold", "Threshold", "Adjustments", true),
|
||||
def("blur", "Blur", "Blur and sharpen", true),
|
||||
def("blurDirectional", "Blur Directional", "Blur and sharpen", true),
|
||||
def("slopeBlur", "Slope Blur", "Blur and sharpen", true),
|
||||
def("sharpen", "Sharpen", "Blur and sharpen", true),
|
||||
def("warp", "Warp", "Distort", true),
|
||||
def("matFinishGrind", "MatFinish Grind", "Material finish", false),
|
||||
def("matFinishRaw", "MatFinish Raw", "Material finish", false),
|
||||
def("matFinishSanded", "MatFinish Sanded", "Material finish", false),
|
||||
def("matFinishHammered", "MatFinish Hammered", "Material finish", false),
|
||||
];
|
||||
|
||||
fn norm(s: &str) -> String {
|
||||
s.to_ascii_lowercase().replace([' ', '_', '-', '/'], "")
|
||||
}
|
||||
|
||||
/// The library filter `id` (case and separators ignored; labels work too).
|
||||
pub fn find(id: &str) -> Option<&'static FilterDef> {
|
||||
let n = norm(id);
|
||||
FILTERS.iter().find(|f| norm(f.id) == n || norm(f.label) == n)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"filter.list",
|
||||
"List filters",
|
||||
[],
|
||||
None,
|
||||
"{} — the filter library: id, label, group, whether masks take it, default parameters",
|
||||
always,
|
||||
|_, _| Ok(Value::Array(
|
||||
FILTERS
|
||||
.iter()
|
||||
.map(|f| json!({"id": f.id, "label": f.label, "group": f.group, "mask": f.mask, "defaults": build(f.id, &Value::Null).ok()}))
|
||||
.collect()
|
||||
))
|
||||
)]
|
||||
}
|
||||
|
||||
/// The effect for library filter `id` with its defaults, then the parameters in `p`.
|
||||
pub fn build(id: &str, p: &Value) -> Result<EffectKind> {
|
||||
let cmd = "effect.add.filter";
|
||||
let d = find(id).ok_or_else(|| bad(cmd, format!("unknown filter `{id}` (see filter.list)")))?;
|
||||
let mut f = match d.id {
|
||||
"invert" => Filter::Invert,
|
||||
"threshold" => Filter::Threshold { level: 0.5 },
|
||||
"blur" => Filter::Blur { radius: 2.0 },
|
||||
"sharpen" => Filter::Sharpen { amount: 1.0 },
|
||||
"hsl" => Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0 },
|
||||
"contrastLuminosity" => Filter::ContrastLuminosity { contrast: 0.3, luminosity: 0.0 },
|
||||
"colorBalance" => Filter::ColorBalance { shadows: [0.0; 3], midtones: [0.0; 3], highlights: [0.0; 3] },
|
||||
"gradientMap" => Filter::GradientMap { colors: vec![[0.02, 0.02, 0.04], [0.45, 0.16, 0.05], [1.0, 0.85, 0.55]] },
|
||||
"posterize" => Filter::Posterize { levels: 4.0 },
|
||||
"clamp" => Filter::Clamp { min: 0.2, max: 0.8 },
|
||||
"warp" => Filter::Warp { intensity: 16.0, scale: 4.0, seed: 1 },
|
||||
"blurDirectional" => Filter::DirectionalBlur { radius: 16.0, angle: 0.0 },
|
||||
"slopeBlur" => Filter::SlopeBlur { radius: 16.0, scale: 4.0, seed: 1 },
|
||||
"levels" => {
|
||||
let mut l = Levels::default();
|
||||
crate::mask_cmds::levels_from(p, &mut l);
|
||||
return Ok(EffectKind::Levels(l));
|
||||
}
|
||||
finish => return mat_finish(finish).map(EffectKind::Material).ok_or_else(|| bad(cmd, format!("unknown filter `{id}`"))),
|
||||
};
|
||||
apply(p, &mut f, cmd)?;
|
||||
Ok(EffectKind::Filter(f))
|
||||
}
|
||||
|
||||
/// A material finish: procedural roughness and height (tri-planar, so it is seamless).
|
||||
fn mat_finish(id: &str) -> Option<Fill> {
|
||||
let (kind, scale, rough, height) = match id {
|
||||
"matFinishGrind" => (ProceduralKind::Brushed, 6.0, [0.22, 0.42], 0.012),
|
||||
"matFinishRaw" => (ProceduralKind::Clouds, 8.0, [0.45, 0.75], 0.02),
|
||||
"matFinishSanded" => (ProceduralKind::Noise, 3.0, [0.38, 0.58], 0.008),
|
||||
"matFinishHammered" => (ProceduralKind::Hammered, 6.0, [0.25, 0.45], 0.08),
|
||||
_ => return None,
|
||||
};
|
||||
let pattern = Procedural { scale, ..Procedural::new(kind) };
|
||||
let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() };
|
||||
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3] });
|
||||
fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3] });
|
||||
Some(fill)
|
||||
}
|
||||
|
||||
/// Scalar parameters of a filter for editors: (param key, label, value, min, max). Colors
|
||||
/// (color balance, gradient map) and the HSL hue have their own editors.
|
||||
pub fn scalar_params(f: &Filter) -> Vec<(&'static str, &'static str, f32, f32, f32)> {
|
||||
match f {
|
||||
Filter::Blur { radius } => vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0)],
|
||||
Filter::Sharpen { amount } => vec![("amount", "Amount", *amount, 0.0, 5.0)],
|
||||
Filter::Threshold { level } => vec![("level", "Level", *level, 0.0, 1.0)],
|
||||
Filter::Hsl { saturation, lightness, .. } => {
|
||||
vec![("saturation", "Saturation", *saturation, -1.0, 1.0), ("lightness", "Lightness", *lightness, -1.0, 1.0)]
|
||||
}
|
||||
Filter::ContrastLuminosity { contrast, luminosity } => {
|
||||
vec![("contrast", "Contrast", *contrast, -1.0, 1.0), ("luminosity", "Luminosity", *luminosity, -1.0, 1.0)]
|
||||
}
|
||||
Filter::Posterize { levels } => vec![("levels", "Steps", *levels, 2.0, 64.0)],
|
||||
Filter::Clamp { min, max } => vec![("min", "Minimum", *min, 0.0, 1.0), ("max", "Maximum", *max, 0.0, 1.0)],
|
||||
Filter::Warp { intensity, scale, seed } => {
|
||||
vec![
|
||||
("intensity", "Intensity (texels at 2K)", *intensity, 0.0, 128.0),
|
||||
("scale", "Noise scale", *scale, 0.5, 64.0),
|
||||
("seed", "Seed", *seed as f32, 0.0, 999.0),
|
||||
]
|
||||
}
|
||||
Filter::DirectionalBlur { radius, angle } => {
|
||||
vec![("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0), ("angle", "Angle (degrees)", *angle, 0.0, 360.0)]
|
||||
}
|
||||
Filter::SlopeBlur { radius, scale, seed } => {
|
||||
vec![
|
||||
("radius", "Intensity (texels at 2K)", *radius, 0.0, 128.0),
|
||||
("scale", "Slope scale", *scale, 0.5, 64.0),
|
||||
("seed", "Seed", *seed as f32, 0.0, 999.0),
|
||||
]
|
||||
}
|
||||
Filter::Invert | Filter::ColorBalance { .. } | Filter::GradientMap { .. } => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the parameters of `f` given in `p` (clamped to their ranges); `effect.set` uses it too.
|
||||
pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> {
|
||||
let set = |slot: &mut f32, key: &str, lo: f32, hi: f32| {
|
||||
if let Some(v) = f32p(p, key) {
|
||||
*slot = v.clamp(lo, hi);
|
||||
}
|
||||
};
|
||||
let seed = |slot: &mut u32| {
|
||||
if let Some(v) = u64p(p, "seed") {
|
||||
*slot = u32::try_from(v).unwrap_or(u32::MAX);
|
||||
}
|
||||
};
|
||||
match f {
|
||||
Filter::Invert => {}
|
||||
Filter::Threshold { level } => set(level, "level", 0.0, 1.0),
|
||||
Filter::Blur { radius } => set(radius, "radius", 0.0, 256.0),
|
||||
Filter::Sharpen { amount } => set(amount, "amount", 0.0, 10.0),
|
||||
Filter::Hsl { hue, saturation, lightness } => {
|
||||
set(hue, "hue", -1.0, 1.0);
|
||||
set(saturation, "saturation", -1.0, 1.0);
|
||||
set(lightness, "lightness", -1.0, 1.0);
|
||||
}
|
||||
Filter::ContrastLuminosity { contrast, luminosity } => {
|
||||
set(contrast, "contrast", -1.0, 1.0);
|
||||
set(luminosity, "luminosity", -1.0, 1.0);
|
||||
}
|
||||
Filter::ColorBalance { shadows, midtones, highlights } => {
|
||||
for (key, slot) in [("shadows", shadows), ("midtones", midtones), ("highlights", highlights)] {
|
||||
if p.get(key).is_some() {
|
||||
let v = color_param(p, key).ok_or_else(|| bad(cmd, format!("`{key}` must be [r, g, b] offsets in -1..1")))?;
|
||||
*slot = v.map(|x| x.clamp(-1.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
Filter::GradientMap { colors } => {
|
||||
if let Some(list) = p.get("colors") {
|
||||
let parsed: Option<Vec<[f32; 3]>> = list.as_array().and_then(|a| a.iter().map(|c| color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect());
|
||||
match parsed {
|
||||
Some(c) if (1..=16).contains(&c.len()) => *colors = c,
|
||||
_ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\")")),
|
||||
}
|
||||
}
|
||||
}
|
||||
Filter::Posterize { levels } => set(levels, "levels", 2.0, 64.0),
|
||||
Filter::Clamp { min, max } => {
|
||||
set(min, "min", 0.0, 1.0);
|
||||
set(max, "max", 0.0, 1.0);
|
||||
}
|
||||
Filter::Warp { intensity, scale, seed: s } => {
|
||||
set(intensity, "intensity", 0.0, 256.0);
|
||||
set(scale, "scale", 0.01, 1000.0);
|
||||
seed(s);
|
||||
}
|
||||
Filter::DirectionalBlur { radius, angle } => {
|
||||
set(radius, "radius", 0.0, 256.0);
|
||||
if let Some(v) = f32p(p, "angle") {
|
||||
*angle = v.rem_euclid(360.0);
|
||||
}
|
||||
}
|
||||
Filter::SlopeBlur { radius, scale, seed: s } => {
|
||||
set(radius, "radius", 0.0, 256.0);
|
||||
set(scale, "scale", 0.01, 1000.0);
|
||||
seed(s);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_filter_builds_and_finds_by_id_or_label() {
|
||||
for f in FILTERS {
|
||||
let kind = build(f.id, &Value::Null).unwrap_or_else(|e| panic!("{}: {e}", f.id));
|
||||
assert_eq!(kind.content_only().is_none(), f.mask, "{}", f.id);
|
||||
assert_eq!(find(f.label).map(|d| d.id), Some(f.id));
|
||||
}
|
||||
assert!(build("nope", &Value::Null).is_err());
|
||||
let EffectKind::Filter(Filter::Posterize { levels }) = build("posterize", &json!({"levels": 1000})).unwrap() else { panic!() };
|
||||
assert_eq!(levels, 64.0);
|
||||
assert!(build("gradientMap", &json!({"colors": []})).is_err());
|
||||
assert!(build("colorBalance", &json!({"shadows": "x"})).is_err());
|
||||
let EffectKind::Filter(Filter::GradientMap { colors }) = build("gradientMap", &json!({"colors": [[0, 0, 0], "#ffffff"]})).unwrap() else { panic!() };
|
||||
assert_eq!(colors.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//! without a screenshot.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, Source};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, Projection, Source};
|
||||
|
||||
use crate::Session;
|
||||
use crate::session::StackTarget;
|
||||
@@ -19,17 +19,23 @@ fn source_json(s: &Source) -> Value {
|
||||
}
|
||||
|
||||
fn fill_json(f: &Fill) -> Value {
|
||||
json!({
|
||||
let mut v = json!({
|
||||
"projection": f.projection.label(),
|
||||
"sources": f.sources.iter().map(|(c, s)| (c.id().to_string(), source_json(s))).collect::<serde_json::Map<_, _>>(),
|
||||
})
|
||||
});
|
||||
if let Projection::Decal(d) = &f.projection {
|
||||
v["decal"] = json!(d);
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// A mask or content (`content`) effect.
|
||||
fn effect_json(s: &Session, e: &Effect, content: bool) -> Value {
|
||||
let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity });
|
||||
match &e.kind {
|
||||
EffectKind::Generator(g) => ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }),
|
||||
EffectKind::Generator(g) => {
|
||||
ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert })
|
||||
}
|
||||
EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]),
|
||||
EffectKind::Paint if content => {
|
||||
ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>())
|
||||
@@ -37,8 +43,14 @@ fn effect_json(s: &Session, e: &Effect, content: bool) -> Value {
|
||||
EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)),
|
||||
EffectKind::Fill { source, .. } => ej["source"] = source_json(source),
|
||||
EffectKind::Material(f) => ej["fill"] = fill_json(f),
|
||||
EffectKind::Filter(Filter::Hsl { hue, saturation, lightness }) => ej["hsl"] = json!([hue, saturation, lightness]),
|
||||
EffectKind::Filter(Filter::Blur { radius }) => ej["radius"] = json!(radius),
|
||||
EffectKind::Filter(f) => {
|
||||
ej["filter"] = json!(f);
|
||||
match f {
|
||||
Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]),
|
||||
Filter::Blur { radius } => ej["radius"] = json!(radius),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ej
|
||||
@@ -68,7 +80,8 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
|
||||
}
|
||||
if matches!(l.kind, LayerKind::Paint) {
|
||||
// Sorted: the store is a hash map, and inspect output must be stable.
|
||||
let mut painted: Vec<(&str, usize)> = s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect();
|
||||
let mut painted: Vec<(&str, usize)> =
|
||||
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect();
|
||||
painted.sort_unstable();
|
||||
v["painted"] = json!(painted.iter().map(|(c, n)| json!({ "channel": c, "tiles": n })).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
@@ -14,7 +14,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("layer.copy", "Copy layer(s)", ["Layers"], Some("Ctrl+C"), "{layer?}", has_layer, copy),
|
||||
cmd!("layer.cut", "Cut layer(s)", ["Layers"], Some("Ctrl+X"), "{layer?}", has_layer, cut),
|
||||
cmd!("layer.paste", "Paste layer(s)", ["Layers"], Some("Ctrl+V"), "{} — above the selection, in the active texture set", can_paste, paste),
|
||||
cmd!("layer.flatten", "Flatten layer", ["Layers"], Some("Ctrl+M"), "{layer?} — a fill or masked paint layer becomes a plain paint layer", has_layer, flatten),
|
||||
cmd!(
|
||||
"layer.flatten",
|
||||
"Flatten layer",
|
||||
["Layers"],
|
||||
Some("Ctrl+M"),
|
||||
"{layer?} — a fill or masked paint layer becomes a plain paint layer",
|
||||
has_layer,
|
||||
flatten
|
||||
),
|
||||
cmd!(
|
||||
"layer.instantiateAll",
|
||||
"Instantiate across texture sets",
|
||||
@@ -156,22 +164,8 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into()));
|
||||
}
|
||||
s.update();
|
||||
let cache = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let size = cache.size;
|
||||
let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect();
|
||||
let empty = Default::default();
|
||||
let inputs = texturecraft_compose::Inputs {
|
||||
project: &s.doc.project,
|
||||
ts,
|
||||
mesh: &s.mesh,
|
||||
gbuf: &cache.gbuf,
|
||||
pixels: &s.doc.pixels,
|
||||
baked: s.doc.baked.get(&ts).unwrap_or(&empty),
|
||||
preview: None,
|
||||
images: &s.images,
|
||||
bounds: s.mesh.bounds(),
|
||||
};
|
||||
let flat = texturecraft_compose::flatten_layer(&inputs, id, &tiles).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?;
|
||||
let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size;
|
||||
let flat = s.flatten(ts, id).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?;
|
||||
s.edit("Flatten layer", |s| {
|
||||
for c in Channel::ALL {
|
||||
s.doc.pixels.layers.remove(&(id, c));
|
||||
@@ -196,6 +190,28 @@ fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per
|
||||
/// channel over the set's covered tiles. None for folders or a set not ready.
|
||||
pub(crate) fn flatten(&self, ts: usize, id: LayerId) -> Option<Vec<texturecraft_compose::eval::FlatTile>> {
|
||||
let cache = self.caches.get(ts)?;
|
||||
let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect();
|
||||
let empty = Default::default();
|
||||
let inputs = texturecraft_compose::Inputs {
|
||||
project: &self.doc.project,
|
||||
ts,
|
||||
mesh: &self.mesh,
|
||||
gbuf: &cache.gbuf,
|
||||
pixels: &self.doc.pixels,
|
||||
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
|
||||
preview: None,
|
||||
images: &self.images,
|
||||
bounds: self.mesh.bounds(),
|
||||
};
|
||||
texturecraft_compose::flatten_layer(&inputs, id, &tiles)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resample every painted image of texture set `ts` to `size` (after a size change).
|
||||
pub(crate) fn resample_set(s: &mut Session, ts: usize, size: (u32, u32)) {
|
||||
let ids: Vec<LayerId> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
|
||||
|
||||
@@ -9,8 +9,11 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod bake_cmds;
|
||||
pub mod camera_cmds;
|
||||
pub mod commands;
|
||||
pub mod decal_cmds;
|
||||
pub mod file_cmds;
|
||||
pub mod filter_lib;
|
||||
pub mod inspect;
|
||||
pub mod instance_cmds;
|
||||
pub mod layer_cmds;
|
||||
@@ -35,7 +38,7 @@ pub use bake_cmds::{BakeMesh, BakeMeshes, BakeTask};
|
||||
pub use commands::{CommandSpec, command_specs, execute, find};
|
||||
pub use path_tool::PathState;
|
||||
pub use project_cmds::sample_session;
|
||||
pub use session::{CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
|
||||
pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
|
||||
|
||||
pub use texturecraft_bake as bake;
|
||||
pub use texturecraft_compose as compose;
|
||||
|
||||
@@ -29,15 +29,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("mask.invert", "Invert mask", ["Layers", "Mask"], None, "{layer?}", has_layer, invert),
|
||||
cmd!("mask.clear", "Clear mask", ["Layers", "Mask"], None, "{layer?}", has_layer, clear),
|
||||
cmd!("mask.remove", "Remove mask", ["Layers", "Mask"], None, "{layer?}", has_layer, remove),
|
||||
cmd!(
|
||||
"effect.add.paint",
|
||||
"Add paint",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, target?: mask|content, name?}",
|
||||
has_layer,
|
||||
|s, p| push_effect(s, p, EffectKind::Paint, BlendMode::Normal)
|
||||
),
|
||||
cmd!("effect.add.paint", "Add paint", ["Layers", "Effects"], None, "{layer?, target?: mask|content, name?}", has_layer, |s, p| push_effect(
|
||||
s,
|
||||
p,
|
||||
EffectKind::Paint,
|
||||
BlendMode::Normal
|
||||
)),
|
||||
cmd!(
|
||||
"effect.add.fill",
|
||||
"Add fill",
|
||||
@@ -70,7 +67,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add filter",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, target?: mask|content, name?, filter?: invert|threshold|blur|sharpen|hsl, level?, radius?, amount?, hue?: turns -1..1, saturation?: -1..1, lightness?: -1..1}",
|
||||
"{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, intensity?, scale?, seed?, angle?} — material finishes go on the content",
|
||||
has_layer,
|
||||
add_filter
|
||||
),
|
||||
@@ -97,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit effect",
|
||||
[],
|
||||
None,
|
||||
"{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, radius?, amount?, hue?, saturation?, lightness?, tolerance?}",
|
||||
"{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -333,7 +330,7 @@ fn add_generator(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
push_effect(s, p, EffectKind::Generator(g), blend)
|
||||
}
|
||||
|
||||
fn levels_from(p: &Value, l: &mut Levels) {
|
||||
pub(crate) fn levels_from(p: &Value, l: &mut Levels) {
|
||||
for (k, slot) in [("inLow", &mut l.in_low), ("inHigh", &mut l.in_high), ("gamma", &mut l.gamma), ("outLow", &mut l.out_low), ("outHigh", &mut l.out_high)] {
|
||||
if let Some(v) = f32p(p, k) {
|
||||
*slot = if k == "gamma" { v.clamp(0.01, 10.0) } else { v.clamp(0.0, 1.0) };
|
||||
@@ -348,29 +345,16 @@ fn add_levels(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn add_filter(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = match strp(p, "filter").unwrap_or("invert") {
|
||||
"invert" => Filter::Invert,
|
||||
"threshold" => Filter::Threshold { level: f32p(p, "level").unwrap_or(0.5).clamp(0.0, 1.0) },
|
||||
"blur" => Filter::Blur { radius: f32p(p, "radius").unwrap_or(2.0).clamp(0.0, 64.0) },
|
||||
"sharpen" => Filter::Sharpen { amount: f32p(p, "amount").unwrap_or(1.0).clamp(0.0, 10.0) },
|
||||
"hsl" => {
|
||||
let mut f = Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0 };
|
||||
hsl_from(p, &mut f);
|
||||
f
|
||||
}
|
||||
other => return Err(bad("effect.add.filter", format!("unknown filter `{other}`"))),
|
||||
};
|
||||
push_effect(s, p, EffectKind::Filter(f), BlendMode::Normal)
|
||||
}
|
||||
|
||||
fn hsl_from(p: &Value, f: &mut Filter) {
|
||||
if let Filter::Hsl { hue, saturation, lightness } = f {
|
||||
for (k, slot) in [("hue", hue), ("saturation", saturation), ("lightness", lightness)] {
|
||||
if let Some(v) = f32p(p, k) {
|
||||
*slot = v.clamp(-1.0, 1.0);
|
||||
}
|
||||
}
|
||||
let id = strp(p, "filter").unwrap_or("invert");
|
||||
let kind = crate::filter_lib::build(id, p)?;
|
||||
// Library filters are named after their shelf entry (material finishes are fill effects).
|
||||
let mut p = p.clone();
|
||||
if name_param(&p).is_none()
|
||||
&& let (Some(d), Some(o)) = (crate::filter_lib::find(id), p.as_object_mut())
|
||||
{
|
||||
o.insert("name".into(), json!(d.label));
|
||||
}
|
||||
push_effect(s, &p, kind, BlendMode::Normal)
|
||||
}
|
||||
|
||||
fn add_compare(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -425,7 +409,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
match &mut e.kind {
|
||||
EffectKind::Generator(g) => generator_from(p, g),
|
||||
EffectKind::Levels(l) => levels_from(p, l),
|
||||
EffectKind::Filter(f @ Filter::Hsl { .. }) => hsl_from(p, f),
|
||||
EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?,
|
||||
EffectKind::Fill { source, .. } => {
|
||||
if let Some(a) = anchor {
|
||||
*source = a;
|
||||
@@ -435,21 +419,6 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
*source = Source::Uniform([x.clamp(0.0, 1.0); 3]);
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(Filter::Threshold { level }) => {
|
||||
if let Some(x) = f32p(p, "level") {
|
||||
*level = x.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(Filter::Blur { radius }) => {
|
||||
if let Some(x) = f32p(p, "radius") {
|
||||
*radius = x.clamp(0.0, 256.0);
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(Filter::Sharpen { amount }) => {
|
||||
if let Some(x) = f32p(p, "amount") {
|
||||
*amount = x.clamp(0.0, 10.0);
|
||||
}
|
||||
}
|
||||
EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => {
|
||||
if let Some(x) = f32p(p, "tolerance") {
|
||||
*tolerance = x.clamp(0.0, 1.0);
|
||||
|
||||
@@ -10,6 +10,7 @@ use texturecraft_compose::PixelStore;
|
||||
use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet};
|
||||
|
||||
use crate::commands::{CommandSpec, always, has_layer};
|
||||
use crate::materials::Place;
|
||||
use crate::session::{Document, StackTarget};
|
||||
use crate::{EngineError, Result, Session, cmd};
|
||||
|
||||
@@ -19,7 +20,15 @@ pub const SMART_MATERIAL_EXT: &str = "tcmat";
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("material.save", "Create smart material", ["Layers"], None, "{layer?, path: .tcmat file, name?}", has_layer, save),
|
||||
cmd!("material.load", "Add smart material from file", [], None, "{path: .tcmat file}", always, load),
|
||||
cmd!(
|
||||
"material.load",
|
||||
"Add smart material from file",
|
||||
[],
|
||||
None,
|
||||
"{path: .tcmat file, above?: layer id, inside?: bool, index?: n} — above the selection by default, or placed like material.apply",
|
||||
always,
|
||||
load
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -83,8 +92,18 @@ impl Session {
|
||||
|
||||
/// Add a smart material file above the selection (one undo step). Returns the new layer.
|
||||
pub fn add_smart_material_bytes(&mut self, bytes: &[u8]) -> Result<LayerId> {
|
||||
self.add_smart_material_bytes_at(bytes, Place::Selection)
|
||||
}
|
||||
|
||||
/// [`Session::add_smart_material_bytes`] at `place` (shelf drag and drop).
|
||||
pub fn add_smart_material_bytes_at(&mut self, bytes: &[u8], place: Place) -> Result<LayerId> {
|
||||
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?;
|
||||
let root = pf.project.texture_sets.first().and_then(|t| t.stack.last().copied()).ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?;
|
||||
let root = pf
|
||||
.project
|
||||
.texture_sets
|
||||
.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>>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
|
||||
let src = Document { project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: resources.clone() };
|
||||
let id = self.edit("Add smart material", |s| {
|
||||
@@ -95,6 +114,7 @@ impl Session {
|
||||
let sel = s.selected_layer();
|
||||
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
|
||||
let id = crate::layer_ops::copy_tree(&src, root, &mut s.doc, ts, sel, inside, 0)?;
|
||||
place.apply(s, id)?;
|
||||
s.selected.insert(ts, id);
|
||||
s.target = StackTarget::Content;
|
||||
Ok(id)
|
||||
@@ -128,7 +148,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = strp(p, "path").ok_or_else(|| bad("material.load", "`path` is required"))?;
|
||||
let bytes = std::fs::read(path).map_err(|e| bad("material.load", format!("cannot read {path}: {e}")))?;
|
||||
let id = s.add_smart_material_bytes(&bytes)?;
|
||||
let id = s.add_smart_material_bytes_at(&bytes, Place::from_params(p))?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
|
||||
@@ -96,8 +96,8 @@ pub const MATERIALS: &[SmartMaterial] = &[
|
||||
m("velvet", "Velvet", FABRIC, [0.12, 0.015, 0.09], 0.0, 0.9),
|
||||
// Ceramic and glass.
|
||||
m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08),
|
||||
m("glass", "Glass Clear", GLASS, [0.02, 0.022, 0.022], 0.0, 0.03),
|
||||
m("glass_frosted", "Glass Frosted", GLASS, [0.6, 0.64, 0.64], 0.0, 0.45),
|
||||
m("glass", "Glass Clear", GLASS, [0.88, 0.9, 0.9], 0.0, 0.03),
|
||||
m("glass_frosted", "Glass Frosted", GLASS, [0.84, 0.88, 0.88], 0.0, 0.45),
|
||||
m("car_paint", "Car Paint", PLASTIC, [0.45, 0.025, 0.03], 0.0, 0.4),
|
||||
// Organic.
|
||||
m("skin", "Skin", ORGANIC, [0.56, 0.35, 0.27], 0.0, 0.5),
|
||||
@@ -367,9 +367,9 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
|
||||
),
|
||||
),
|
||||
"wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])),
|
||||
// ---- Glass (opaque approximation; uses Opacity when the texture set has it) ------------
|
||||
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Opacity, u(0.2))])),
|
||||
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Opacity, u(0.6))])),
|
||||
// ---- Glass (the Transmission channel; the base color tints the light going through) ----
|
||||
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])),
|
||||
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])),
|
||||
// ---- Smart materials ----------------------------------------------------------------
|
||||
"steel_painted_worn" => {
|
||||
let mut v = build(b, "steel")?;
|
||||
@@ -568,7 +568,24 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
|
||||
s.selected.insert(ts, gid);
|
||||
gid
|
||||
};
|
||||
match place {
|
||||
place.apply(s, top)?;
|
||||
Ok(top)
|
||||
})
|
||||
}
|
||||
|
||||
impl Place {
|
||||
/// From `above` (+ `inside`) or `index` params; the selection by default.
|
||||
pub(crate) fn from_params(p: &serde_json::Value) -> Place {
|
||||
match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "index")) {
|
||||
(Some(above), _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)),
|
||||
(None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)),
|
||||
(None, None) => Place::Selection,
|
||||
}
|
||||
}
|
||||
|
||||
/// Move `top` (just added above the selection) to this place.
|
||||
pub(crate) fn apply(self, s: &mut Session, top: LayerId) -> Result<()> {
|
||||
match self {
|
||||
Place::Selection => {}
|
||||
Place::Above(target, inside) => s.doc.project.move_above(top, Some(target), inside)?,
|
||||
Place::Index(i) => {
|
||||
@@ -576,8 +593,8 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
|
||||
s.doc.project.move_layer(top, i)?;
|
||||
}
|
||||
}
|
||||
Ok(top)
|
||||
})
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -638,7 +655,8 @@ mod tests {
|
||||
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
|
||||
let chans = |s: &Session| s.doc.project.texture_sets[0].channel_list();
|
||||
let before = chans(&s);
|
||||
let cases: [(&str, &[Channel]); 5] = [
|
||||
let cases: [(&str, &[Channel]); 6] = [
|
||||
("glass", &[Transmission]),
|
||||
("car_paint", &[CoatWeight, CoatRoughness]),
|
||||
("velvet", &[SheenWeight, SheenColor, SheenRoughness]),
|
||||
("steel_brushed_aniso", &[AnisotropyLevel, AnisotropyAngle]),
|
||||
@@ -652,9 +670,6 @@ mod tests {
|
||||
s.undo().unwrap();
|
||||
assert_eq!(chans(&s), before, "{id}: one undo step");
|
||||
}
|
||||
// Classic channels a set lacks stay out (glass uses Opacity).
|
||||
apply(&mut s, "glass").unwrap();
|
||||
assert_eq!(chans(&s), before);
|
||||
apply(&mut s, "car_paint").unwrap();
|
||||
s.update();
|
||||
let coat = |s: &Session| s.caches[0].composite.value(CoatWeight, 64, 64)[0];
|
||||
|
||||
@@ -11,7 +11,7 @@ use texturecraft_paint::{
|
||||
rasterize,
|
||||
};
|
||||
|
||||
use crate::session::{ActiveStroke, FillMode, Session, StackTarget, Tool};
|
||||
use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool};
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
impl Session {
|
||||
@@ -104,6 +104,13 @@ impl Session {
|
||||
// Clone and smudge read the composite: bring it up to date first.
|
||||
self.update();
|
||||
}
|
||||
// Cloning from the selected layer reads that layer alone.
|
||||
let layer_source = match self.selected_layer() {
|
||||
Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer => {
|
||||
Some(self.flatten(ts, id).ok_or_else(|| EngineError::Other("clone from a paint or fill layer (folders have no content of their own)".into()))?)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let before = self.doc.clone();
|
||||
let target = if quick_mask {
|
||||
None
|
||||
@@ -151,7 +158,10 @@ impl Session {
|
||||
}
|
||||
m => m,
|
||||
};
|
||||
canvas.pickup = Some(Pickup::new(mode, cache.composite.clone(), cache.gbuf.clone(), values.keys().copied()));
|
||||
canvas.pickup = Some(match &layer_source {
|
||||
Some(flat) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()),
|
||||
None => Pickup::new(mode, cache.composite.clone(), cache.gbuf.clone(), values.keys().copied()),
|
||||
});
|
||||
if tool == Tool::Clone
|
||||
&& let Some(src) = self.tool.clone_source.as_mut()
|
||||
{
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! noise). Cheap enough for lazily rendered thumbnails.
|
||||
|
||||
use texturecraft_compose::pattern::{Coords, procedural, world_noise};
|
||||
use texturecraft_core::{Channel, EffectKind, Filter, Generator, GeneratorKind, LayerKind, Mask, MaskBackground, Project, Projection, Source, blend1};
|
||||
use texturecraft_core::{
|
||||
Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project,
|
||||
Projection, Source, TextureSet, blend1,
|
||||
};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::materials::{Builder, build};
|
||||
@@ -115,6 +118,65 @@ pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
)
|
||||
}
|
||||
|
||||
/// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K).
|
||||
fn magnified(f: Filter, k: f32) -> Filter {
|
||||
match f {
|
||||
Filter::Blur { radius } => Filter::Blur { radius: radius * k },
|
||||
Filter::DirectionalBlur { radius, angle } => Filter::DirectionalBlur { radius: radius * k, angle },
|
||||
Filter::SlopeBlur { radius, scale, seed } => Filter::SlopeBlur { radius: radius * k, scale, seed },
|
||||
Filter::Warp { intensity, scale, seed } => Filter::Warp { intensity: intensity * k, scale, seed },
|
||||
f => f,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview of library filter `id` (see [`crate::filter_lib`]): a sample material (colorful
|
||||
/// clouds, checker roughness, cell bumps) with the filter on its content, composited by the
|
||||
/// compositor on a plane and laid over the sphere (None for an unknown id).
|
||||
pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
let res = u32::try_from(size).ok()?.max(1);
|
||||
let kind = match crate::filter_lib::build(id, &serde_json::Value::Null).ok()? {
|
||||
EffectKind::Filter(f) => EffectKind::Filter(magnified(f, 2048.0 / res as f32)),
|
||||
k => k,
|
||||
};
|
||||
let mesh = texturecraft_geom::primitives::plane(2.0, 2);
|
||||
let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res);
|
||||
let mut p = Project::new("preview", "");
|
||||
p.texture_sets.push(TextureSet::new("preview", 0, res));
|
||||
let procedural = |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high };
|
||||
let mut fill = Fill::default();
|
||||
fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1]));
|
||||
fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3]));
|
||||
fill.sources.insert(Channel::Height, procedural(ProceduralKind::Cells, 3.0, [-0.12; 3], [0.12; 3]));
|
||||
let mut layer = Layer::new(p.alloc_id(), "sample", LayerKind::Fill(fill), &CHANNELS);
|
||||
layer.content_effects.push(Effect::new(p.alloc_id(), kind));
|
||||
p.insert_layer(0, layer, None, false).ok()?;
|
||||
let (pixels, baked, images) = (Default::default(), Default::default(), Default::default());
|
||||
let inp = texturecraft_compose::Inputs {
|
||||
project: &p,
|
||||
ts: 0,
|
||||
mesh: &mesh,
|
||||
gbuf: &gbuf,
|
||||
pixels: &pixels,
|
||||
baked: &baked,
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: mesh.bounds(),
|
||||
};
|
||||
let mut out = texturecraft_compose::Composite::new(&CHANNELS, res);
|
||||
texturecraft_compose::composite_tiles(&inp, &mut out, &texturecraft_compose::all_tiles(res, res));
|
||||
Some(
|
||||
sphere_normals(size)
|
||||
.enumerate()
|
||||
.map(|(i, n)| {
|
||||
n?;
|
||||
let (x, y) = ((i % size) as u32, (i / size) as u32);
|
||||
let [base, metal, rough, height] = CHANNELS.map(|c| out.value(c, x, y));
|
||||
Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] })
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id).
|
||||
pub fn smart_mask(id: &str, size: usize) -> Option<Vec<Option<f32>>> {
|
||||
let (bg, fx) = crate::smart_masks::preset(id)?;
|
||||
@@ -138,6 +200,13 @@ mod tests {
|
||||
let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id));
|
||||
assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id);
|
||||
}
|
||||
assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none());
|
||||
assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none());
|
||||
for f in crate::filter_lib::FILTERS {
|
||||
let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id));
|
||||
let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id));
|
||||
assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id);
|
||||
}
|
||||
let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap());
|
||||
assert!(plain != warped, "the warp shows in its preview");
|
||||
}
|
||||
}
|
||||
@@ -48,12 +48,7 @@ fn new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn material(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?;
|
||||
let place = match (u64p(p, "above"), u64p(p, "index")) {
|
||||
(Some(above), _) => Place::Above(texturecraft_core::LayerId(above), boolp(p, "inside").unwrap_or(false)),
|
||||
(None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)),
|
||||
(None, None) => Place::Selection,
|
||||
};
|
||||
let l = crate::materials::apply_at(s, id, place)?;
|
||||
let l = crate::materials::apply_at(s, id, Place::from_params(p))?;
|
||||
Ok(json!({ "layer": l.0 }))
|
||||
}
|
||||
|
||||
|
||||
@@ -206,6 +206,9 @@ pub struct ToolState {
|
||||
/// Clone tool source (Painter: V + click).
|
||||
#[serde(default)]
|
||||
pub clone_source: Option<CloneSource>,
|
||||
/// What the Clone tool copies: the composite or the selected layer alone.
|
||||
#[serde(default)]
|
||||
pub clone_from: CloneFrom,
|
||||
/// The Path tool's curve being edited.
|
||||
#[serde(default)]
|
||||
pub path: crate::path_tool::PathState,
|
||||
@@ -215,6 +218,16 @@ fn default_smudge_strength() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
/// What the Clone tool copies (Painter's clone source modes).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum CloneFrom {
|
||||
/// Everything the texture set shows.
|
||||
#[default]
|
||||
Composite,
|
||||
/// The selected layer only (its content and mask; empty parts copy nothing).
|
||||
Layer,
|
||||
}
|
||||
|
||||
/// Where the Clone tool copies from, in texture coordinates.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CloneSource {
|
||||
@@ -237,6 +250,7 @@ impl Default for ToolState {
|
||||
stencil: None,
|
||||
smudge_strength: default_smudge_strength(),
|
||||
clone_source: None,
|
||||
clone_from: CloneFrom::Composite,
|
||||
path: Default::default(),
|
||||
};
|
||||
t.values.insert(Channel::BaseColor, [0.8, 0.8, 0.8]);
|
||||
|
||||
@@ -7,7 +7,7 @@ use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{Alignment, BrushAlpha, alphas};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
|
||||
use crate::session::{CloneSource, FillMode, Tool};
|
||||
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Brush settings",
|
||||
[],
|
||||
None,
|
||||
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryX?, symmetryY?, symmetryZ?, minSize?, smudgeStrength?: 0..100, particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
|
||||
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryX?, symmetryY?, symmetryZ?, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
|
||||
always,
|
||||
brush
|
||||
),
|
||||
@@ -164,6 +164,13 @@ fn brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = f32p(p, "smudgeStrength") {
|
||||
s.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = strp(p, "cloneSource") {
|
||||
s.tool.clone_from = match v {
|
||||
"composite" => CloneFrom::Composite,
|
||||
"layer" => CloneFrom::Layer,
|
||||
other => return Err(bad("tool.brush", format!("unknown clone source `{other}`: use composite or layer"))),
|
||||
};
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(brush_json(s))
|
||||
}
|
||||
@@ -181,6 +188,7 @@ pub(crate) fn brush_json(s: &Session) -> Value {
|
||||
},
|
||||
"backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z],
|
||||
"smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles,
|
||||
"cloneSource": if s.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Display settings",
|
||||
[],
|
||||
None,
|
||||
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, scatterColor?: [r,g,b] (linear) | \"#rrggbb\", scatterRadius? (0..1 of the mesh radius)}",
|
||||
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, scatterColor?: [r,g,b] (linear) | \"#rrggbb\", scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}",
|
||||
always,
|
||||
display
|
||||
),
|
||||
@@ -180,6 +180,7 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
("sharpen", &mut d.sharpen, 0.0, 1.0),
|
||||
("grain", &mut d.grain, 0.0, 1.0),
|
||||
("scatterRadius", &mut d.scatter_radius, 0.0, 1.0),
|
||||
("ior", &mut d.ior, 1.0, 3.0),
|
||||
] {
|
||||
if let Some(v) = f32p(p, k) {
|
||||
*slot = v.clamp(lo, hi);
|
||||
@@ -194,12 +195,26 @@ fn display(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(b) = boolp(p, "shadows") {
|
||||
d.shadows = b;
|
||||
}
|
||||
if let Some(dof) = p.get("dof") {
|
||||
if let Some(b) = boolp(dof, "enabled") {
|
||||
d.dof.enabled = b;
|
||||
}
|
||||
if let Some(v) = f32p(dof, "focusDistance") {
|
||||
d.dof.focus_distance = v.clamp(0.0, 1e6);
|
||||
}
|
||||
if let Some(v) = f32p(dof, "aperture") {
|
||||
d.dof.aperture = v.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
for (k, slot) in [("postEffects", &mut d.post_effects), ("taa", &mut d.taa), ("specGloss", &mut d.spec_gloss), ("parallax", &mut d.parallax)] {
|
||||
if let Some(b) = boolp(p, k) {
|
||||
*slot = b;
|
||||
}
|
||||
}
|
||||
s.camera.fov = s.doc.project.display.fov;
|
||||
// The field of view applies to the view only when set (a saved camera keeps its own).
|
||||
if f32p(p, "fov").is_some() {
|
||||
s.camera.fov = s.doc.project.display.fov;
|
||||
}
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! The filter library, geometry decals, cloning from the selected layer, placing saved smart
|
||||
//! materials, anchors inside a content stack and instances across texture set resolutions,
|
||||
//! through engine commands.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection};
|
||||
use texturecraft_engine::geom::NO_TRI;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
|
||||
s.viewport = Vec2::new(400.0, 400.0);
|
||||
s.camera.yaw = 0.0;
|
||||
s.camera.pitch = 0.0;
|
||||
s.update();
|
||||
s
|
||||
}
|
||||
|
||||
fn id(v: Value, key: &str) -> LayerId {
|
||||
LayerId(v[key].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// Composite value of `c` under a viewport point.
|
||||
fn at(s: &mut Session, c: Channel, x: f32, y: f32) -> [f32; 3] {
|
||||
s.update();
|
||||
let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap();
|
||||
let (w, h) = s.caches[0].size;
|
||||
s.caches[0].composite.value(c, (hit.uv.x * w as f32) as u32, (hit.uv.y * h as f32) as u32)
|
||||
}
|
||||
|
||||
fn red(v: [f32; 3]) -> bool {
|
||||
v[0] > 0.85 && v[1] < 0.15
|
||||
}
|
||||
|
||||
fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_library_adds_every_filter_and_edits_its_parameters() {
|
||||
let mut s = session();
|
||||
let list = execute(&mut s, "filter.list", &Value::Null).unwrap();
|
||||
let ids: Vec<&str> = list.as_array().unwrap().iter().map(|f| f["id"].as_str().unwrap()).collect();
|
||||
for want in [
|
||||
"warp",
|
||||
"blurDirectional",
|
||||
"sharpen",
|
||||
"hsl",
|
||||
"levels",
|
||||
"contrastLuminosity",
|
||||
"colorBalance",
|
||||
"gradientMap",
|
||||
"posterize",
|
||||
"clamp",
|
||||
"slopeBlur",
|
||||
"matFinishGrind",
|
||||
] {
|
||||
assert!(ids.contains(&want), "{want} missing from {ids:?}");
|
||||
}
|
||||
let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1], "roughness": 0.4})).unwrap(), "layer");
|
||||
let before = at(&mut s, Channel::BaseColor, 200.0, 200.0);
|
||||
for f in list.as_array().unwrap() {
|
||||
let fid = f["id"].as_str().unwrap();
|
||||
let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect");
|
||||
let (owner, e) = s.doc.project.effect(eid).unwrap();
|
||||
assert_eq!(owner, layer);
|
||||
assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry");
|
||||
assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid));
|
||||
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
|
||||
}
|
||||
// A gradient map recolors the content; effect.set edits it and inspect shows it.
|
||||
let gm =
|
||||
id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect");
|
||||
let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0);
|
||||
assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}");
|
||||
execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap();
|
||||
assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95);
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err());
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains("GradientMap"), "inspect shows filter parameters");
|
||||
execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap();
|
||||
// Posterize on the mask; its steps are clamped.
|
||||
let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap();
|
||||
assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post)));
|
||||
assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0));
|
||||
// Material finishes fill the content's roughness and height.
|
||||
let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect");
|
||||
assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin));
|
||||
assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height)));
|
||||
assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err());
|
||||
// A directional blur, slope blur and warp composite without trouble on a sphere.
|
||||
for (fid, extra) in [("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"radius": 30})), ("warp", json!({"intensity": 50}))] {
|
||||
let mut p = json!({"filter": fid, "target": "content"});
|
||||
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
|
||||
execute(&mut s, "effect.add.filter", &p).unwrap();
|
||||
}
|
||||
assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
|
||||
let mut s = session();
|
||||
// A red disc on a transparent background.
|
||||
let name = s
|
||||
.import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] }))
|
||||
.unwrap();
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": "missing.png"})).is_err());
|
||||
assert!(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 2, "y": 2})).is_err(), "off the mesh");
|
||||
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
|
||||
let layer = id(r.clone(), "layer");
|
||||
assert!((r["decal"]["size"][1].as_f64().unwrap() - 0.5).abs() < 1e-6);
|
||||
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
|
||||
assert!(matches!(f.projection, Projection::Decal(_)));
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed");
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there");
|
||||
// The image's transparent corners leave the surface as it was.
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 200.0 + 30.0, 200.0 - 30.0)));
|
||||
// Bigger, then moved along its plane, then re-placed with a click.
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap();
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0)));
|
||||
execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap();
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "moved away");
|
||||
let r = execute(&mut s, "layer.decal.set", &json!({"x": 170, "y": 180})).unwrap();
|
||||
assert_eq!(r["decal"]["offset"], json!([0.0, 0.0]), "re-placing resets the offset");
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal");
|
||||
// Not a decal; one undo step per edit.
|
||||
let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err());
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_copies_the_selected_layer_alone_when_asked() {
|
||||
let mut s = session();
|
||||
execute(&mut s, "tool.paint", &Value::Null).unwrap();
|
||||
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap();
|
||||
let low = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[160, 200]]})).unwrap();
|
||||
let top = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "tool.clone", &Value::Null).unwrap();
|
||||
assert!(execute(&mut s, "tool.brush", &json!({"cloneSource": "nope"})).is_err());
|
||||
let r = execute(&mut s, "tool.brush", &json!({"size": 6, "cloneSource": "layer"})).unwrap();
|
||||
assert_eq!(r["cloneSource"], "layer");
|
||||
execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap();
|
||||
// The empty top layer has nothing to copy.
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[240, 200]]})).unwrap();
|
||||
assert!(!red(at(&mut s, Channel::BaseColor, 240.0, 200.0)));
|
||||
assert!(s.doc.pixels.layer(top, Channel::BaseColor).is_none_or(|i| i.allocated_count() == 0));
|
||||
// From the composite it copies what shows.
|
||||
execute(&mut s, "tool.brush", &json!({"cloneSource": "composite"})).unwrap();
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[240, 200]]})).unwrap();
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 240.0, 200.0)));
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
// The painted layer itself copies its paint.
|
||||
execute(&mut s, "layer.select", &json!({"layer": low.0})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"cloneSource": "layer"})).unwrap();
|
||||
execute(&mut s, "tool.stroke", &json!({"points": [[240, 200]]})).unwrap();
|
||||
assert!(red(at(&mut s, Channel::BaseColor, 240.0, 200.0)));
|
||||
assert_eq!(s.tool.clone_from, texturecraft_engine::CloneFrom::Layer);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn saved_smart_materials_load_where_they_are_dropped() {
|
||||
let mut s = session();
|
||||
let a = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.9})).unwrap(), "layer");
|
||||
let b = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer");
|
||||
let dir = std::env::temp_dir().join(format!("tc_gaps_{}", std::process::id()));
|
||||
let path = dir.join("rough.tcmat").display().to_string();
|
||||
execute(&mut s, "material.save", &json!({"layer": a.0, "path": path})).unwrap();
|
||||
let stack = |s: &Session| s.doc.project.texture_sets[0].stack.clone();
|
||||
let bottom = id(execute(&mut s, "material.load", &json!({"path": path, "index": 0})).unwrap(), "layer");
|
||||
assert_eq!(stack(&s).first(), Some(&bottom));
|
||||
let above = id(execute(&mut s, "material.load", &json!({"path": path, "above": a.0})).unwrap(), "layer");
|
||||
let st = stack(&s);
|
||||
assert_eq!(st.iter().position(|x| *x == above), st.iter().position(|x| *x == a).map(|i| i + 1));
|
||||
assert_eq!(st.last(), Some(&b));
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert!(!stack(&s).contains(&above), "one undo step");
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchors_inside_a_content_stack_read_the_content_there() {
|
||||
let mut s = session();
|
||||
let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.4})).unwrap(), "layer");
|
||||
let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low.0})).unwrap(), "effect");
|
||||
execute(&mut s, "effect.add.fill", &json!({"layer": low.0, "target": "content", "height": 0.8})).unwrap();
|
||||
let reader = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "layer.blend", &json!({"layer": reader.0, "channel": "all", "enabled": false})).unwrap();
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": reader.0, "channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap();
|
||||
assert!((at(&mut s, Channel::Roughness, 200.0, 200.0)[0] - 0.4).abs() < 2e-3, "the anchor reads the content before the fill above it");
|
||||
assert!((at(&mut s, Channel::Height, 200.0, 200.0)[0] - 0.8).abs() < 2e-3);
|
||||
// Moved to the top of the content stack, it records the layer's full result again.
|
||||
execute(&mut s, "effect.remove", &json!({"effect": anchor.0})).unwrap();
|
||||
let end = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low.0})).unwrap(), "effect");
|
||||
execute(&mut s, "layer.fill.set", &json!({"layer": reader.0, "channel": "roughness", "anchor": end.0, "anchorChannel": "height"})).unwrap();
|
||||
assert!((at(&mut s, Channel::Roughness, 200.0, 200.0)[0] - 0.8).abs() < 2e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_show_their_source_in_sets_of_another_resolution() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
|
||||
s.update();
|
||||
let src = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer");
|
||||
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
execute(&mut s, "tool.brush", &json!({"size": 100, "hardness": 100})).unwrap();
|
||||
let pts: Vec<[f32; 2]> = (0..=20).flat_map(|i| (0..=20).map(move |j| [i as f32 / 20.0, j as f32 / 20.0])).collect();
|
||||
execute(&mut s, "tool.strokeUv", &json!({"points": pts})).unwrap();
|
||||
execute(&mut s, "layer.instance", &json!({"layer": src.0, "ts": 1})).unwrap();
|
||||
let reds = |s: &mut Session| {
|
||||
s.update();
|
||||
let c = &s.caches[1];
|
||||
let (w, h) = c.size;
|
||||
(0..h)
|
||||
.flat_map(|y| (0..w).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| c.gbuf.tri[(y * w + x) as usize] != NO_TRI && red(c.composite.value(Channel::BaseColor, x, y)))
|
||||
.count()
|
||||
};
|
||||
let same = reds(&mut s);
|
||||
assert!(same > 1000, "{same}");
|
||||
execute(&mut s, "textureSet.resolution", &json!({"ts": 1, "resolution": 128})).unwrap();
|
||||
let half = reds(&mut s);
|
||||
assert!(half * 5 > same && half * 3 < same, "about a quarter of the texels: {same} -> {half}");
|
||||
}
|
||||
@@ -53,6 +53,16 @@ fn read_inner(bytes: &[u8], base: Option<&Path>) -> Result<RawMesh> {
|
||||
return Err(FormatError::TooLarge(format!("the glTF scene has more than {MAX_NODE_VISITS} node instances")));
|
||||
}
|
||||
let m = parent * Mat4::from_cols_array_2d(&node.transform().matrix());
|
||||
if let Some(cam) = node.camera()
|
||||
&& raw.cameras.len() < super::MAX_CAMERAS
|
||||
{
|
||||
let (fov, ortho_half_height) = match cam.projection() {
|
||||
gltf::camera::Projection::Perspective(p) => (p.yfov().to_degrees(), None),
|
||||
gltf::camera::Projection::Orthographic(o) => (40.0, Some(o.ymag())),
|
||||
};
|
||||
let name = cam.name().or_else(|| node.name()).map_or_else(|| format!("Camera {}", raw.cameras.len() + 1), str::to_string);
|
||||
raw.cameras.push(super::RawCamera { name, eye: m.transform_point3(Vec3::ZERO), forward: m.transform_vector3(Vec3::NEG_Z), fov, ortho_half_height });
|
||||
}
|
||||
if let Some(mesh) = node.mesh() {
|
||||
let part = node.name().or_else(|| mesh.name()).unwrap_or_default();
|
||||
for prim in mesh.primitives() {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! model, COLLADA node, USD Mesh prim; unnamed parts take the file stem), materials contiguous,
|
||||
//! glTF UV convention (origin top-left, v down),
|
||||
//! normals (computed when missing), vertex colors (glTF, OBJ, PLY), UVs (auto-unwrapped when
|
||||
//! missing) and MikkTSpace tangents.
|
||||
//! missing) and MikkTSpace tangents. glTF cameras come along as the project's camera list.
|
||||
|
||||
mod dae;
|
||||
mod fbx;
|
||||
@@ -43,6 +43,21 @@ pub const MESH_EXTENSIONS: [&str; 11] = ["gltf", "glb", "fbx", "dae", "usd", "us
|
||||
pub struct ImportedMesh {
|
||||
pub mesh: Mesh,
|
||||
pub report: MeshReport,
|
||||
/// Cameras of the file (glTF), as orbit cameras around the mesh.
|
||||
pub cameras: Vec<texturecraft_core::Camera>,
|
||||
}
|
||||
|
||||
/// Cameras read from a file (at most [`MAX_CAMERAS`]).
|
||||
pub(crate) const MAX_CAMERAS: usize = 64;
|
||||
|
||||
/// A camera as a file places it: world position, view direction, vertical field of view
|
||||
/// (degrees, perspective) or half view height (orthographic).
|
||||
pub(crate) struct RawCamera {
|
||||
pub name: String,
|
||||
pub eye: Vec3,
|
||||
pub forward: Vec3,
|
||||
pub fov: f32,
|
||||
pub ortho_half_height: Option<f32>,
|
||||
}
|
||||
|
||||
/// What the importer found and fixed, for the import dialog.
|
||||
@@ -74,6 +89,7 @@ pub(crate) struct RawMesh {
|
||||
/// Triangles (vertex indices) per (material, part name); an empty part is unnamed.
|
||||
pub groups: Vec<(String, String, Vec<u32>)>,
|
||||
pub warnings: Vec<String>,
|
||||
pub cameras: Vec<RawCamera>,
|
||||
}
|
||||
|
||||
impl RawMesh {
|
||||
@@ -238,7 +254,7 @@ fn read(file_name: &str, bytes: &[u8], base: Option<&std::path::Path>) -> Result
|
||||
/// Positions, submeshes (materials contiguous), normals and colors of a raw mesh, validated;
|
||||
/// plus its warnings and UVs (the mesh's UVs and tangents are left empty).
|
||||
fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
|
||||
let RawMesh { positions, normals, uvs, colors, groups, warnings } = raw;
|
||||
let RawMesh { positions, normals, uvs, colors, groups, warnings, .. } = raw;
|
||||
check_vertices(positions.len())?;
|
||||
check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?;
|
||||
let mut mesh = Mesh { positions, ..Mesh::default() };
|
||||
@@ -283,7 +299,8 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec<String>, Option<Vec<Vec2>>)> {
|
||||
}
|
||||
|
||||
/// Complete a raw mesh: submeshes, normals, UVs, tangents, validation and the report.
|
||||
pub(crate) fn finish(raw: RawMesh) -> Result<ImportedMesh> {
|
||||
pub(crate) fn finish(mut raw: RawMesh) -> Result<ImportedMesh> {
|
||||
let raw_cameras = std::mem::take(&mut raw.cameras);
|
||||
let (mut mesh, mut warnings, uvs) = geometry(raw)?;
|
||||
let uvs_generated = match uvs {
|
||||
Some(uv) if uv.len() == mesh.positions.len() => {
|
||||
@@ -302,7 +319,38 @@ pub(crate) fn finish(raw: RawMesh) -> Result<ImportedMesh> {
|
||||
};
|
||||
mesh.validate()?;
|
||||
let report = report(&mesh, uvs_generated, warnings);
|
||||
Ok(ImportedMesh { mesh, report })
|
||||
let cameras = orbit_cameras(&raw_cameras, &mesh);
|
||||
Ok(ImportedMesh { mesh, report, cameras })
|
||||
}
|
||||
|
||||
/// File cameras as orbit cameras: the target is where the view axis passes the mesh center
|
||||
/// (at least a tenth of the mesh size ahead). shortcut: camera roll is dropped (orbit cameras
|
||||
/// keep +Y up); keep a free camera transform if imported rolls matter.
|
||||
fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec<texturecraft_core::Camera> {
|
||||
let (lo, hi) = mesh.bounds();
|
||||
let (center, radius) = ((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(1e-3));
|
||||
raw.iter()
|
||||
.filter(|c| c.eye.is_finite() && c.forward.is_finite())
|
||||
.filter_map(|c| {
|
||||
let f = c.forward.try_normalize()?;
|
||||
let distance = (center - c.eye).dot(f).max(radius * 0.1);
|
||||
let target = c.eye + f * distance;
|
||||
let fov = match c.ortho_half_height {
|
||||
Some(h) => 2.0 * (h.abs() / distance).atan().to_degrees(),
|
||||
None => c.fov,
|
||||
};
|
||||
let fov = if fov.is_finite() { fov.clamp(5.0, 150.0) } else { 40.0 };
|
||||
Some(texturecraft_core::Camera {
|
||||
name: c.name.clone(),
|
||||
target: target.to_array(),
|
||||
yaw: (-f.x).atan2(-f.z),
|
||||
pitch: (-f.y).clamp(-1.0, 1.0).asin().clamp(-89f32.to_radians(), 89f32.to_radians()),
|
||||
distance,
|
||||
fov,
|
||||
ortho: c.ortho_half_height.is_some(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Area-weighted smooth normals over welded positions (UV seams do not split shading).
|
||||
|
||||
@@ -413,3 +413,32 @@ fn high_poly_import_skips_unwrap_and_rejects_garbage() {
|
||||
assert!(import_high_poly_bytes("x.ply", b"ply\nformat ascii 1.0\nelement vertex 99999999\n").is_err());
|
||||
assert!(import_high_poly_bytes("x.txt", b"").is_err());
|
||||
}
|
||||
|
||||
/// The embedded scene plus a perspective camera looking at the triangle along -Z and an unnamed
|
||||
/// orthographic one looking straight down.
|
||||
fn gltf_with_cameras() -> Vec<u8> {
|
||||
let mut json: serde_json::Value = serde_json::from_slice(&embedded_gltf()).unwrap();
|
||||
json["cameras"] = serde_json::json!([
|
||||
{ "name": "Shot", "type": "perspective", "perspective": { "yfov": 0.8, "znear": 0.1 } },
|
||||
{ "type": "orthographic", "orthographic": { "xmag": 1.0, "ymag": 0.5, "znear": 0.1, "zfar": 10.0 } }
|
||||
]);
|
||||
let nodes = json["nodes"].as_array_mut().unwrap();
|
||||
nodes.push(serde_json::json!({ "camera": 0, "translation": [-1.5, 0.5, 4.0] }));
|
||||
nodes.push(serde_json::json!({ "camera": 1, "translation": [-1.5, 5.5, 0.0], "rotation": [-std::f32::consts::FRAC_1_SQRT_2, 0.0, 0.0, std::f32::consts::FRAC_1_SQRT_2] }));
|
||||
json["scenes"][0]["nodes"] = serde_json::json!([0, 2, 3]);
|
||||
serde_json::to_vec(&json).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_cameras_become_orbit_cameras() {
|
||||
let im = import_mesh_bytes("scene.gltf", &gltf_with_cameras()).unwrap();
|
||||
let [shot, top] = im.cameras.as_slice() else { panic!("{:?}", im.cameras) };
|
||||
let near = |a: f32, b: f32| (a - b).abs() < 1e-3;
|
||||
assert_eq!(shot.name, "Shot");
|
||||
assert!(!shot.ortho && near(shot.fov, 0.8f32.to_degrees()) && near(shot.distance, 4.0), "{shot:?}");
|
||||
assert!(near(shot.yaw, 0.0) && near(shot.pitch, 0.0) && shot.target.iter().zip([-1.5, 0.5, 0.0]).all(|(a, b)| near(*a, b)), "{shot:?}");
|
||||
assert_eq!(top.name, "Camera 2");
|
||||
assert!(top.ortho && near(top.distance, 5.0) && near(top.fov, 2.0 * 0.1f32.atan().to_degrees()), "{top:?}");
|
||||
assert!(near(top.pitch, 89f32.to_radians()), "looking down, pitch clamped: {top:?}");
|
||||
assert!(import_mesh_bytes("scene.gltf", &embedded_gltf()).unwrap().cameras.is_empty());
|
||||
}
|
||||
@@ -175,6 +175,18 @@ impl Bvh {
|
||||
self.tris.is_empty()
|
||||
}
|
||||
|
||||
/// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range
|
||||
/// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children
|
||||
/// `first` and `first + 1`.
|
||||
pub fn nodes(&self) -> impl ExactSizeIterator<Item = (Vec3, Vec3, u32, u32)> + '_ {
|
||||
self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count))
|
||||
}
|
||||
|
||||
/// Triangle vertices in BVH order, and the original triangle index of each.
|
||||
pub fn triangles(&self) -> (&[[Vec3; 3]], &[u32]) {
|
||||
(&self.tris, &self.order)
|
||||
}
|
||||
|
||||
fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option<f32> {
|
||||
let t0 = (lo - o) * inv;
|
||||
let t1 = (hi - o) * inv;
|
||||
|
||||
@@ -6,9 +6,10 @@ use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use texturecraft_compose::Composite;
|
||||
use texturecraft_compose::eval::FlatTile;
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_geom::{NO_TRI, UvGBuffer};
|
||||
use texturecraft_texel::{TileImage, from_u16, to_u16};
|
||||
use texturecraft_texel::{TILE_AREA, TileImage, from_u16, to_u16};
|
||||
|
||||
use crate::commit::{dec, enc};
|
||||
|
||||
@@ -28,6 +29,9 @@ pub struct Pickup {
|
||||
pub mode: PickupMode,
|
||||
/// The composite when the stroke began (what the stroke reads).
|
||||
source: Composite,
|
||||
/// How much of `source` there is to read per texel (a single layer's coverage); None reads
|
||||
/// everywhere.
|
||||
coverage: Option<TileImage>,
|
||||
/// Texels outside the texture set's UV islands are never read.
|
||||
gbuf: Arc<UvGBuffer>,
|
||||
/// Straight values per painted channel; the stroke alpha lives in the stroke canvas.
|
||||
@@ -52,7 +56,41 @@ impl Pickup {
|
||||
/// A pickup reading `source` (whose resolution is the stroke's) for `channels`.
|
||||
pub fn new(mode: PickupMode, source: Composite, gbuf: Arc<UvGBuffer>, channels: impl IntoIterator<Item = Channel>) -> Pickup {
|
||||
let values = channels.into_iter().map(|c| (c, TileImage::new(source.resolution, source.height, c.components()))).collect();
|
||||
Pickup { mode, source, gbuf, values, prev: None, reads: Vec::new(), read_values: Vec::new() }
|
||||
Pickup { mode, source, coverage: None, gbuf, values, prev: None, reads: Vec::new(), read_values: Vec::new() }
|
||||
}
|
||||
|
||||
/// A pickup reading one layer alone, from its flattened tiles (premultiplied values plus
|
||||
/// coverage per channel, see `texturecraft_compose::flatten_layer`) at `size`: where the
|
||||
/// layer is empty the stroke deposits nothing.
|
||||
pub fn from_layer(mode: PickupMode, flat: &[FlatTile], size: (u32, u32), gbuf: Arc<UvGBuffer>, channels: impl IntoIterator<Item = Channel>) -> Pickup {
|
||||
let channels: Vec<Channel> = channels.into_iter().collect();
|
||||
let mut source = Composite::with_size(&channels, size.0, size.1);
|
||||
let mut coverage = TileImage::new(size.0, size.1, 1);
|
||||
for (c, (tx, ty), data) in flat {
|
||||
let Some(img) = source.channels.get_mut(c) else { continue };
|
||||
let (n, kind) = (c.components(), c.kind());
|
||||
let mut straight = vec![0u16; TILE_AREA * n];
|
||||
let Some(cov) = coverage.tile_mut(*tx, *ty, &[0]) else { continue };
|
||||
for (o, px) in data.chunks_exact(n + 1).enumerate() {
|
||||
let a = px.get(n).copied().unwrap_or(0);
|
||||
if a == 0 {
|
||||
continue;
|
||||
}
|
||||
let inv = 1.0 / from_u16(a);
|
||||
for (k, v) in px.iter().take(n).enumerate() {
|
||||
if let Some(slot) = straight.get_mut(o * n + k) {
|
||||
*slot = enc(kind, dec(kind, *v) * inv);
|
||||
}
|
||||
}
|
||||
if let Some(slot) = cov.get_mut(o) {
|
||||
*slot = (*slot).max(a);
|
||||
}
|
||||
}
|
||||
img.set_tile(*tx, *ty, Some(Arc::new(straight)));
|
||||
}
|
||||
let mut p = Pickup::new(mode, source, gbuf, channels);
|
||||
p.coverage = Some(coverage);
|
||||
p
|
||||
}
|
||||
|
||||
fn covered(&self, x: u32, y: u32) -> bool {
|
||||
@@ -84,12 +122,15 @@ impl Pickup {
|
||||
self.reads.clear();
|
||||
self.read_values.clear();
|
||||
for &(x, y, a) in texels {
|
||||
let a = a * strength;
|
||||
let (sx, sy) = (i64::from(x) + shift[0], i64::from(y) + shift[1]);
|
||||
if !(a > 0.0 && (0..w).contains(&sx) && (0..h).contains(&sy) && self.covered(sx as u32, sy as u32)) {
|
||||
continue;
|
||||
}
|
||||
let (sx, sy) = (sx as u32, sy as u32);
|
||||
let a = a * strength * self.coverage.as_ref().map_or(1.0, |c| from_u16(c.get(sx, sy)[0]));
|
||||
if a <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Smudge reads what the stroke shows so far: carried values over the source.
|
||||
let m = if smudge { from_u16(alpha.get(sx, sy)[0]) } else { 0.0 };
|
||||
for (c, img) in &self.values {
|
||||
@@ -175,6 +216,30 @@ mod tests {
|
||||
assert!(!p.stamp(&mut alpha, &disc(5, 5, 2), [5.0, 5.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_clones_copy_only_where_the_layer_has_paint() {
|
||||
let (_, g) = setup(|_| 0.0);
|
||||
// The layer: roughness 0.8 at half coverage on the left half (premultiplied).
|
||||
let mut data = vec![0u16; TILE_AREA * 2];
|
||||
for y in 0..TILE {
|
||||
for x in 0..TILE / 2 {
|
||||
let o = (y * TILE + x) as usize * 2;
|
||||
data[o] = to_u16(0.4);
|
||||
data[o + 1] = to_u16(0.5);
|
||||
}
|
||||
}
|
||||
let flat = vec![(Channel::Roughness, (0, 0), data)];
|
||||
let mut p = Pickup::from_layer(PickupMode::Clone { offset: [-30, 0] }, &flat, (TILE, TILE), g.clone(), [Channel::Roughness]);
|
||||
let mut alpha = TileImage::new(TILE, TILE, 1);
|
||||
assert!(p.stamp(&mut alpha, &disc(45, 32, 3), [45.0, 32.0]));
|
||||
let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 45, 32)[0];
|
||||
assert!((v - 0.8).abs() < 1e-3, "straight value: {v}");
|
||||
assert!((from_u16(alpha.get(45, 32)[0]) - 0.5).abs() < 1e-3, "the layer's coverage scales the stroke");
|
||||
// Reading the layer's empty right half deposits nothing.
|
||||
let mut q = Pickup::from_layer(PickupMode::Clone { offset: [30, 0] }, &flat, (TILE, TILE), g, [Channel::Roughness]);
|
||||
assert!(!q.stamp(&mut TileImage::new(TILE, TILE, 1), &disc(20, 32, 3), [20.0, 32.0]), "the source is the empty half");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smudge_drags_values_along_the_stroke() {
|
||||
let (c, g) = setup(|x| if x < 20 { 1.0 } else { 0.0 });
|
||||
|
||||
@@ -0,0 +1,873 @@
|
||||
//! GPU path tracing for Rendering mode: the CPU tracer in [`crate::trace`] (the oracle) ported to
|
||||
//! compute shaders (`shaders/trace.wgsl`, `shaders/trace_post.wgsl`), same light transport and
|
||||
//! the same random streams, so both converge to the same image.
|
||||
//!
|
||||
//! The mesh, its BVH and the environment's importance-sampling tables live in storage buffers;
|
||||
//! materials are copies of the renderer's display textures (`compose::display` packing, one array
|
||||
//! layer per texture set plus one for the default material). [`GpuTracer::pass`] adds samples per
|
||||
//! pixel to float accumulation buffers; [`GpuTracer::resolve`] runs the à-trous denoiser and tone
|
||||
//! maps into an RGBA8 texture, so the app shows renders without reading them back.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll, Waker};
|
||||
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use texturecraft_compose::DisplayKind;
|
||||
use texturecraft_geom::glam::{Vec3, Vec4};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
use crate::Renderer;
|
||||
use crate::ibl::EnvImage;
|
||||
use crate::trace::{TraceDisplay, TraceScene, TraceSettings};
|
||||
|
||||
/// Texture sets the tracer takes (one more array layer holds the default material).
|
||||
pub const MAX_SETS: usize = 255;
|
||||
/// Depth of the shader's BVH traversal stack (`STACK` in trace.wgsl).
|
||||
const STACK: usize = 64;
|
||||
const KINDS: usize = DisplayKind::ALL.len();
|
||||
/// Bytes of the trace uniform: [`Head`] then 256 texture-set entries (`MAX_SETS` in trace.wgsl).
|
||||
const PARAMS_SIZE: u64 = (size_of::<Head>() + 256 * 16) as u64;
|
||||
/// Post uniform slots: resolve and denoise init, then the five à-trous steps.
|
||||
const STEPS: [u32; 6] = [0, 1, 2, 4, 8, 16];
|
||||
const WORKGROUP: u32 = 8;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
struct Head {
|
||||
inv_vp: [f32; 16],
|
||||
forward: [f32; 4],
|
||||
size: [u32; 4],
|
||||
cfg: [u32; 4],
|
||||
env: [f32; 4],
|
||||
sigma: [f32; 4],
|
||||
eye: [f32; 4],
|
||||
lens: [f32; 4],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
struct PostRaw {
|
||||
size: [u32; 4],
|
||||
display: [f32; 4],
|
||||
}
|
||||
|
||||
struct Geometry {
|
||||
mesh: Arc<Mesh>,
|
||||
tri_set: Arc<Vec<usize>>,
|
||||
nodes: wgpu::Buffer,
|
||||
tris: wgpu::Buffer,
|
||||
verts: wgpu::Buffer,
|
||||
}
|
||||
|
||||
struct EnvGpu {
|
||||
image: Arc<EnvImage>,
|
||||
view: wgpu::TextureView,
|
||||
cdf: wgpu::Buffer,
|
||||
/// Whether `cdf` holds importance-sampling tables.
|
||||
light: bool,
|
||||
}
|
||||
|
||||
/// Copies of the renderer's display textures, one array per [`DisplayKind`].
|
||||
struct Materials {
|
||||
rev: u64,
|
||||
arrays: Vec<(wgpu::Texture, wgpu::TextureView)>,
|
||||
/// Per layer: width, height, mask of kinds that are 1×1 placeholders.
|
||||
info: Vec<[f32; 3]>,
|
||||
}
|
||||
|
||||
struct Accum {
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Radiance + luminance², albedo + hits, normal + depth, environment of misses.
|
||||
acc: [wgpu::Buffer; 4],
|
||||
/// Ping-pong demodulated radiance + variance for the denoiser.
|
||||
illum: [wgpu::Buffer; 2],
|
||||
}
|
||||
|
||||
/// Scene constants of the trace uniform.
|
||||
struct SceneConst {
|
||||
spec_gloss: bool,
|
||||
eps: f32,
|
||||
sigma: Vec3,
|
||||
rotation: f32,
|
||||
heights: Vec<f32>,
|
||||
ior: f32,
|
||||
/// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole).
|
||||
lens: [f32; 2],
|
||||
}
|
||||
|
||||
/// The GPU path tracer: pipelines, the uploaded scene and one view's accumulation.
|
||||
pub struct GpuTracer {
|
||||
trace_bgl: wgpu::BindGroupLayout,
|
||||
post_bgl: wgpu::BindGroupLayout,
|
||||
trace_pipe: wgpu::ComputePipeline,
|
||||
init_pipe: wgpu::ComputePipeline,
|
||||
step_pipe: wgpu::ComputePipeline,
|
||||
resolve_pipe: wgpu::ComputePipeline,
|
||||
params: wgpu::Buffer,
|
||||
post: wgpu::Buffer,
|
||||
post_stride: u32,
|
||||
geometry: Option<Geometry>,
|
||||
env: Option<EnvGpu>,
|
||||
materials: Option<Materials>,
|
||||
acc: Option<Accum>,
|
||||
scene: Option<SceneConst>,
|
||||
bind: Option<wgpu::BindGroup>,
|
||||
samples: u32,
|
||||
}
|
||||
|
||||
/// The error a scope caught, if wgpu reported it at once (native backends do).
|
||||
fn caught(f: impl Future<Output = Option<wgpu::Error>>) -> Option<wgpu::Error> {
|
||||
let mut f = std::pin::pin!(f);
|
||||
match f.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||
Poll::Ready(e) => e,
|
||||
Poll::Pending => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `f` with validation and out-of-memory errors turned into an `Err` instead of wgpu's
|
||||
/// default handler (which panics).
|
||||
fn scoped<T>(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T) -> Result<T, String> {
|
||||
let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let invalid = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let out = f();
|
||||
let errors = [caught(invalid.pop()), caught(oom.pop())];
|
||||
match errors.into_iter().flatten().next() {
|
||||
Some(e) => Err(format!("GPU path tracing: {what}: {e}")),
|
||||
None => Ok(out),
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(binding: u32, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }
|
||||
}
|
||||
|
||||
fn storage(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
|
||||
entry(binding, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None })
|
||||
}
|
||||
|
||||
fn texture(binding: u32, view_dimension: wgpu::TextureViewDimension) -> wgpu::BindGroupLayoutEntry {
|
||||
entry(binding, wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension, multisampled: false })
|
||||
}
|
||||
|
||||
fn buffer(device: &wgpu::Device, label: &str, contents: &[u8]) -> wgpu::Buffer {
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE })
|
||||
}
|
||||
|
||||
fn bits(v: Vec3, w: u32) -> [u32; 4] {
|
||||
[v.x.to_bits(), v.y.to_bits(), v.z.to_bits(), w]
|
||||
}
|
||||
|
||||
/// Depth of the deepest leaf (the root is 1), or None for a malformed tree.
|
||||
fn bvh_depth(nodes: &[(Vec3, Vec3, u32, u32)]) -> Option<usize> {
|
||||
let mut stack = vec![(0usize, 1usize)];
|
||||
let mut deepest = 0;
|
||||
let mut visited = 0usize;
|
||||
while let Some((i, d)) = stack.pop() {
|
||||
visited += 1;
|
||||
let &(_, _, first, count) = nodes.get(i)?;
|
||||
deepest = deepest.max(d);
|
||||
if count == 0 && visited <= nodes.len() {
|
||||
stack.push((first as usize, d + 1));
|
||||
stack.push((first as usize + 1, d + 1));
|
||||
}
|
||||
}
|
||||
(visited <= nodes.len()).then_some(deepest)
|
||||
}
|
||||
|
||||
impl GpuTracer {
|
||||
/// Whether `device` can run the tracer (compute shaders and enough bindings: not WebGL2).
|
||||
pub fn supported(device: &wgpu::Device) -> bool {
|
||||
let l = device.limits();
|
||||
l.max_storage_buffers_per_shader_stage >= 8
|
||||
&& l.max_storage_textures_per_shader_stage >= 1
|
||||
&& l.max_sampled_textures_per_shader_stage > KINDS as u32
|
||||
&& l.max_compute_invocations_per_workgroup >= WORKGROUP * WORKGROUP
|
||||
&& l.max_compute_workgroup_size_x >= WORKGROUP
|
||||
&& l.max_compute_workgroup_size_y >= WORKGROUP
|
||||
&& l.max_uniform_buffer_binding_size >= PARAMS_SIZE
|
||||
&& l.max_texture_array_layers >= 2
|
||||
}
|
||||
|
||||
pub fn new(device: &wgpu::Device) -> Result<GpuTracer, String> {
|
||||
if !Self::supported(device) {
|
||||
return Err("GPU path tracing needs compute shaders (WebGPU, Vulkan, Metal or DirectX 12)".into());
|
||||
}
|
||||
scoped(device, "pipelines", || Self::create(device))
|
||||
}
|
||||
|
||||
fn create(device: &wgpu::Device) -> GpuTracer {
|
||||
let uniform = |binding, dynamic| {
|
||||
entry(binding, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: dynamic, min_binding_size: None })
|
||||
};
|
||||
let mut trace_entries = vec![uniform(0, false), storage(1, true), storage(2, true), storage(3, true), storage(4, true)];
|
||||
trace_entries.extend((5..9).map(|b| storage(b, false)));
|
||||
trace_entries.push(texture(9, wgpu::TextureViewDimension::D2));
|
||||
trace_entries.extend((10..10 + KINDS as u32).map(|b| texture(b, wgpu::TextureViewDimension::D2Array)));
|
||||
let trace_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("tc_trace"), entries: &trace_entries });
|
||||
let mut post_entries = vec![uniform(0, true)];
|
||||
post_entries.extend((1..6).map(|b| storage(b, true)));
|
||||
post_entries.push(storage(6, false));
|
||||
post_entries.push(entry(
|
||||
7,
|
||||
wgpu::BindingType::StorageTexture {
|
||||
access: wgpu::StorageTextureAccess::WriteOnly,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
},
|
||||
));
|
||||
let post_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("tc_trace_post"), entries: &post_entries });
|
||||
let module =
|
||||
|label, src: &str| device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) });
|
||||
let trace_module = module("tc_trace", include_str!("shaders/trace.wgsl"));
|
||||
let post_module = module("tc_trace_post", include_str!("shaders/trace_post.wgsl"));
|
||||
let pipe = |bgl: &wgpu::BindGroupLayout, m: &wgpu::ShaderModule, entry_point: &str| {
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some(entry_point),
|
||||
bind_group_layouts: &[Some(bgl)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some(entry_point),
|
||||
layout: Some(&layout),
|
||||
module: m,
|
||||
entry_point: Some(entry_point),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let post_stride = (size_of::<PostRaw>() as u32).next_multiple_of(device.limits().min_uniform_buffer_offset_alignment.max(1));
|
||||
let uniform_buffer = |label, size| {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
size,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
};
|
||||
GpuTracer {
|
||||
trace_pipe: pipe(&trace_bgl, &trace_module, "trace_main"),
|
||||
init_pipe: pipe(&post_bgl, &post_module, "denoise_init"),
|
||||
step_pipe: pipe(&post_bgl, &post_module, "denoise_step"),
|
||||
resolve_pipe: pipe(&post_bgl, &post_module, "resolve"),
|
||||
trace_bgl,
|
||||
post_bgl,
|
||||
params: uniform_buffer("tc_trace_params", PARAMS_SIZE),
|
||||
post: uniform_buffer("tc_trace_post", u64::from(post_stride) * STEPS.len() as u64),
|
||||
post_stride,
|
||||
geometry: None,
|
||||
env: None,
|
||||
materials: None,
|
||||
acc: None,
|
||||
scene: None,
|
||||
bind: None,
|
||||
samples: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples per pixel accumulated since the last [`GpuTracer::reset`].
|
||||
pub fn samples(&self) -> u32 {
|
||||
self.samples
|
||||
}
|
||||
|
||||
/// Free the scene and accumulation memory, keeping the compiled pipelines.
|
||||
pub fn release(&mut self) {
|
||||
(self.geometry, self.env, self.materials, self.acc, self.scene, self.bind) = (None, None, None, None, None, None);
|
||||
self.samples = 0;
|
||||
}
|
||||
|
||||
/// Upload what changed of `scene`: the mesh and BVH (when the mesh or its texture-set
|
||||
/// mapping changed), the environment and the shading constants.
|
||||
pub fn set_scene(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, scene: &TraceScene) -> Result<(), String> {
|
||||
let limits = device.limits();
|
||||
let max_buf = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
|
||||
let fits = |what: &str, bytes: usize| {
|
||||
if bytes as u64 <= max_buf { Ok(()) } else { Err(format!("the {what} ({} MB) exceeds this GPU's buffer limit", bytes >> 20)) }
|
||||
};
|
||||
let same_geometry = self.geometry.as_ref().is_some_and(|g| Arc::ptr_eq(&g.mesh, &scene.mesh) && g.tri_set == scene.tri_set);
|
||||
if !same_geometry {
|
||||
let nodes: Vec<(Vec3, Vec3, u32, u32)> = scene.bvh.nodes().collect();
|
||||
if bvh_depth(&nodes).is_none_or(|d| d >= STACK) {
|
||||
return Err("the mesh's BVH is too deep for GPU traversal".into());
|
||||
}
|
||||
let (data, verts) = geometry_data(&scene.mesh, &scene.bvh, &scene.tri_set);
|
||||
let (nodes, tris) = data;
|
||||
for (what, b) in [("BVH", nodes.len()), ("triangle list", tris.len()), ("vertex list", verts.len())] {
|
||||
fits(what, b * 16)?;
|
||||
}
|
||||
self.geometry = Some(scoped(device, "mesh upload", || Geometry {
|
||||
mesh: scene.mesh.clone(),
|
||||
tri_set: scene.tri_set.clone(),
|
||||
nodes: buffer(device, "tc_trace_nodes", bytemuck::cast_slice(&nodes)),
|
||||
tris: buffer(device, "tc_trace_tris", bytemuck::cast_slice(&tris)),
|
||||
verts: buffer(device, "tc_trace_verts", bytemuck::cast_slice(&verts)),
|
||||
})?);
|
||||
self.bind = None;
|
||||
}
|
||||
if !self.env.as_ref().is_some_and(|e| Arc::ptr_eq(&e.image, &scene.env)) {
|
||||
let img = &scene.env;
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let valid = w > 0 && h > 0 && img.data.len() >= w * h && img.width.max(img.height) <= limits.max_texture_dimension_2d;
|
||||
let (tw, th, rgba): (u32, u32, Vec<[f32; 4]>) =
|
||||
if valid { (img.width, img.height, img.data.iter().take(w * h).map(|c| [c[0], c[1], c[2], 1.0]).collect()) } else { (1, 1, vec![[0.0; 4]]) };
|
||||
let mut cdf = Vec::new();
|
||||
if let Some(l) = scene.light.as_ref().filter(|l| valid && l.width == w && l.height == h) {
|
||||
cdf.extend_from_slice(&l.rows);
|
||||
cdf.extend_from_slice(&l.cols);
|
||||
cdf.extend_from_slice(&l.prob);
|
||||
}
|
||||
fits("environment table", cdf.len() * 4)?;
|
||||
let light = !cdf.is_empty();
|
||||
if !light {
|
||||
cdf.push(0.0);
|
||||
}
|
||||
let env = scoped(device, "environment upload", || {
|
||||
let tex = device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("tc_trace_env"),
|
||||
size: wgpu::Extent3d { width: tw, height: th, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba32Float,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
bytemuck::cast_slice(&rgba),
|
||||
);
|
||||
EnvGpu {
|
||||
image: scene.env.clone(),
|
||||
view: tex.create_view(&Default::default()),
|
||||
cdf: buffer(device, "tc_trace_cdf", bytemuck::cast_slice(&cdf)),
|
||||
light,
|
||||
}
|
||||
})?;
|
||||
self.env = Some(env);
|
||||
self.bind = None;
|
||||
}
|
||||
self.scene = Some(SceneConst {
|
||||
spec_gloss: scene.spec_gloss,
|
||||
eps: scene.eps,
|
||||
sigma: scene.scatter_sigma,
|
||||
rotation: scene.env_rotation,
|
||||
heights: scene.sets.iter().map(|s| s.height_strength).collect(),
|
||||
ior: scene.ior,
|
||||
lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy the renderer's display textures when their content changed (a GPU-side copy);
|
||||
/// true when it did (samples taken before no longer match the scene).
|
||||
pub fn sync_materials(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
renderer: &Renderer,
|
||||
) -> Result<bool, String> {
|
||||
let rev = renderer.content_rev();
|
||||
if self.materials.as_ref().is_some_and(|m| m.rev == rev) {
|
||||
return Ok(false);
|
||||
}
|
||||
let sets = renderer.display_textures();
|
||||
if sets.len() > MAX_SETS || sets.iter().any(|s| s.len() != KINDS) {
|
||||
return Err(format!("GPU path tracing takes at most {MAX_SETS} texture sets"));
|
||||
}
|
||||
let layers = sets.len() as u32 + 1;
|
||||
let limits = device.limits();
|
||||
if layers > limits.max_texture_array_layers {
|
||||
return Err(format!("this GPU takes at most {} texture sets", limits.max_texture_array_layers.saturating_sub(1)));
|
||||
}
|
||||
let old = self.materials.take();
|
||||
let mut arrays = Vec::with_capacity(KINDS);
|
||||
for (k, kind) in DisplayKind::ALL.into_iter().enumerate() {
|
||||
let size = sets.iter().filter_map(|s| s.get(k)).fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h)));
|
||||
let reuse =
|
||||
old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (size.0, size.1, layers));
|
||||
let (tex, view) = match reuse {
|
||||
Some(a) => a.clone(),
|
||||
None => scoped(device, "material textures", || {
|
||||
let tex = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("tc_trace_material"),
|
||||
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: layers },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: crate::renderer::display_format(kind),
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = tex.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
|
||||
(tex, view)
|
||||
})?,
|
||||
};
|
||||
if reuse.is_none() {
|
||||
self.bind = None;
|
||||
}
|
||||
for (layer, src) in sets.iter().filter_map(|s| s.get(k)).enumerate() {
|
||||
encoder.copy_texture_to_texture(
|
||||
src.as_image_copy(),
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &tex,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: 0, y: 0, z: layer as u32 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::Extent3d { width: src.width(), height: src.height(), depth_or_array_layers: 1 },
|
||||
);
|
||||
}
|
||||
// The default material: one texel of the kind's neutral value.
|
||||
let texel = kind.default_texel();
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &tex,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d { x: 0, y: 0, z: layers - 1 },
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
&texel,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(texel.len() as u32), rows_per_image: Some(1) },
|
||||
wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
|
||||
);
|
||||
arrays.push((tex, view));
|
||||
}
|
||||
let mut info: Vec<[f32; 3]> = sets
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let dims = s.first().map_or((1, 1), |t| (t.width(), t.height()));
|
||||
let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k);
|
||||
[dims.0 as f32, dims.1 as f32, small as f32]
|
||||
})
|
||||
.collect();
|
||||
info.push([1.0, 1.0, 0.0]);
|
||||
self.materials = Some(Materials { rev, arrays, info });
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Start over at `width × height` (the accumulation buffers are cleared or reallocated).
|
||||
pub fn reset(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, width: u32, height: u32) -> Result<(), String> {
|
||||
let (w, h) = (width.clamp(1, 8192), height.clamp(1, 8192));
|
||||
self.samples = 0;
|
||||
if let Some(a) = self.acc.as_ref().filter(|a| (a.width, a.height) == (w, h)) {
|
||||
for b in &a.acc {
|
||||
encoder.clear_buffer(b, 0, None);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.acc = None;
|
||||
self.bind = None;
|
||||
let bytes = u64::from(w) * u64::from(h) * 16;
|
||||
let limits = device.limits();
|
||||
if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) {
|
||||
return Err(format!("a {w}×{h} render exceeds this GPU's buffer limit"));
|
||||
}
|
||||
let buf = |label| {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some(label),
|
||||
size: bytes,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
};
|
||||
self.acc = Some(scoped(device, "accumulation buffers", || Accum {
|
||||
width: w,
|
||||
height: h,
|
||||
acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(buf),
|
||||
illum: ["tc_illum_a", "tc_illum_b"].map(buf),
|
||||
})?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add `spp` samples per pixel (call once per submission: the uniform is rewritten). False
|
||||
/// until a scene, materials and a size are set.
|
||||
pub fn pass(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
cam: &OrbitCamera,
|
||||
settings: &TraceSettings,
|
||||
spp: u32,
|
||||
) -> bool {
|
||||
let (Some(acc), Some(geo), Some(env), Some(mat), Some(sc)) = (&self.acc, &self.geometry, &self.env, &self.materials, &self.scene) else { return false };
|
||||
let bind = self.bind.get_or_insert_with(|| {
|
||||
let mut entries = vec![
|
||||
wgpu::BindGroupEntry { binding: 0, resource: self.params.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: geo.nodes.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: geo.tris.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: geo.verts.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: env.cdf.as_entire_binding() },
|
||||
];
|
||||
entries.extend(acc.acc.iter().zip(5..).map(|(b, binding)| wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }));
|
||||
entries.push(wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(&env.view) });
|
||||
entries
|
||||
.extend(mat.arrays.iter().zip(10..).map(|((_, v), binding)| wgpu::BindGroupEntry { binding, resource: wgpu::BindingResource::TextureView(v) }));
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_trace"), layout: &self.trace_bgl, entries: &entries })
|
||||
});
|
||||
let (w, h) = (acc.width, acc.height);
|
||||
let inv_vp = cam.view_proj(w as f32 / h as f32).inverse();
|
||||
let (sin, cos) = sc.rotation.sin_cos();
|
||||
let head = Head {
|
||||
inv_vp: inv_vp.to_cols_array(),
|
||||
forward: cam.forward().extend(sc.eps).to_array(),
|
||||
size: [w, h, self.samples, spp.max(1)],
|
||||
cfg: [settings.bounces, u32::from(sc.spec_gloss), u32::from(env.light), (mat.info.len() - 1) as u32],
|
||||
env: [sin, cos, 0.0, 0.0],
|
||||
sigma: sc.sigma.extend(0.0).to_array(),
|
||||
eye: cam.eye().extend(1.0).to_array(),
|
||||
lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, 0.0],
|
||||
};
|
||||
let mut sets = [[0.0f32; 4]; 256];
|
||||
for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() {
|
||||
*slot = [m[0], m[1], m[2], sc.heights.get(i).copied().unwrap_or(0.0)];
|
||||
}
|
||||
let mut bytes = bytemuck::bytes_of(&head).to_vec();
|
||||
bytes.extend_from_slice(bytemuck::cast_slice(&sets));
|
||||
queue.write_buffer(&self.params, 0, &bytes);
|
||||
let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_trace"), timestamp_writes: None });
|
||||
cpass.set_pipeline(&self.trace_pipe);
|
||||
cpass.set_bind_group(0, &*bind, &[]);
|
||||
cpass.dispatch_workgroups(w.div_ceil(WORKGROUP), h.div_ceil(WORKGROUP), 1);
|
||||
drop(cpass);
|
||||
self.samples = self.samples.saturating_add(spp.max(1));
|
||||
true
|
||||
}
|
||||
|
||||
/// Display pixels into `out` (an [`GpuTracer::output_texture`] of the render's size):
|
||||
/// denoised when `display.denoise`, tone mapped over the backdrop as [`crate::trace::Tracer::rgba8`].
|
||||
pub fn resolve(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
display: &TraceDisplay,
|
||||
out: &wgpu::TextureView,
|
||||
) -> bool {
|
||||
let Some(acc) = &self.acc else { return false };
|
||||
let flag = |b: bool| if b { 1.0 } else { 0.0 };
|
||||
let disp = [display.exposure, flag(display.aces), display.env_opacity, flag(display.denoise)];
|
||||
let mut bytes = vec![0u8; self.post_stride as usize * STEPS.len()];
|
||||
for (i, step) in STEPS.iter().enumerate() {
|
||||
let raw = PostRaw { size: [acc.width, acc.height, self.samples, *step], display: disp };
|
||||
if let Some(slot) = bytes.get_mut(i * self.post_stride as usize..).and_then(|s| s.get_mut(..size_of::<PostRaw>())) {
|
||||
slot.copy_from_slice(bytemuck::bytes_of(&raw));
|
||||
}
|
||||
}
|
||||
queue.write_buffer(&self.post, 0, &bytes);
|
||||
let post = wgpu::BufferBinding { buffer: &self.post, offset: 0, size: wgpu::BufferSize::new(size_of::<PostRaw>() as u64) };
|
||||
// a: illum[0] → illum[1], b: illum[1] → illum[0].
|
||||
let group = |src: &wgpu::Buffer, dst: &wgpu::Buffer| {
|
||||
let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(post.clone()) }];
|
||||
entries.extend(acc.acc.iter().zip(1..).map(|(b, binding)| wgpu::BindGroupEntry { binding, resource: b.as_entire_binding() }));
|
||||
entries.push(wgpu::BindGroupEntry { binding: 5, resource: src.as_entire_binding() });
|
||||
entries.push(wgpu::BindGroupEntry { binding: 6, resource: dst.as_entire_binding() });
|
||||
entries.push(wgpu::BindGroupEntry { binding: 7, resource: wgpu::BindingResource::TextureView(out) });
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_trace_post"), layout: &self.post_bgl, entries: &entries })
|
||||
};
|
||||
let [i0, i1] = &acc.illum;
|
||||
let (a, b) = (group(i0, i1), group(i1, i0));
|
||||
let groups = (acc.width.div_ceil(WORKGROUP), acc.height.div_ceil(WORKGROUP));
|
||||
let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_trace_post"), timestamp_writes: None });
|
||||
let mut run = |pipe: &wgpu::ComputePipeline, bg: &wgpu::BindGroup, slot: usize| {
|
||||
cpass.set_pipeline(pipe);
|
||||
cpass.set_bind_group(0, bg, &[slot as u32 * self.post_stride]);
|
||||
cpass.dispatch_workgroups(groups.0, groups.1, 1);
|
||||
};
|
||||
if display.denoise {
|
||||
// The five steps alternate b, a, b, a, b, leaving the result in illum[0].
|
||||
run(&self.init_pipe, &a, 0);
|
||||
for slot in 1..STEPS.len() {
|
||||
run(&self.step_pipe, if slot % 2 == 1 { &b } else { &a }, slot);
|
||||
}
|
||||
}
|
||||
run(&self.resolve_pipe, &a, 0);
|
||||
true
|
||||
}
|
||||
|
||||
/// The texture [`GpuTracer::resolve`] writes (RGBA8, sRGB-encoded values, as the CPU tracer's
|
||||
/// `rgba8`): also sampled by the UI and copied for read-back.
|
||||
pub fn output_texture(device: &wgpu::Device, width: u32, height: u32) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("tc_trace_out"),
|
||||
size: wgpu::Extent3d { width: width.clamp(1, 8192), height: height.clamp(1, 8192), depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// A whole render, blocking: `samples` passes at `size`, resolved and read back as RGBA8
|
||||
/// (sRGB) pixels. `renderer` holds the session's texture sets.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn render(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
renderer: &Renderer,
|
||||
scene: &TraceScene,
|
||||
cam: &OrbitCamera,
|
||||
settings: &TraceSettings,
|
||||
display: &TraceDisplay,
|
||||
size: [u32; 2],
|
||||
samples: u32,
|
||||
) -> Result<(u32, u32, Vec<u8>), String> {
|
||||
self.set_scene(device, queue, scene)?;
|
||||
let encoder = || device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_trace") });
|
||||
let mut enc = encoder();
|
||||
self.sync_materials(device, queue, &mut enc, renderer)?;
|
||||
self.reset(device, &mut enc, size[0], size[1])?;
|
||||
queue.submit([enc.finish()]);
|
||||
let (w, h) = self.acc.as_ref().map_or((1, 1), |a| (a.width, a.height));
|
||||
// Several samples per dispatch on small renders; about one at 1080p (short GPU jobs).
|
||||
let chunk = (16_000_000 / (w * h).max(1)).clamp(1, 16);
|
||||
while self.samples < samples {
|
||||
let mut enc = encoder();
|
||||
if !self.pass(device, queue, &mut enc, cam, settings, chunk.min(samples - self.samples)) {
|
||||
return Err("GPU path tracing: the scene is incomplete".into());
|
||||
}
|
||||
queue.submit([enc.finish()]);
|
||||
}
|
||||
let out = Self::output_texture(device, w, h);
|
||||
let mut enc = encoder();
|
||||
self.resolve(device, queue, &mut enc, display, &out.create_view(&Default::default()));
|
||||
queue.submit([enc.finish()]);
|
||||
crate::readback::Readback::blocking(device, queue, &out).ok_or_else(|| "GPU path tracing: could not read the render back".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// GPU buffers of the mesh: (BVH nodes, triangles in BVH order), vertices. An empty mesh gets
|
||||
/// one empty leaf over one degenerate triangle.
|
||||
type GeometryData = ((Vec<[u32; 4]>, Vec<[u32; 4]>), Vec<[f32; 4]>);
|
||||
|
||||
fn geometry_data(mesh: &Mesh, bvh: &texturecraft_geom::Bvh, tri_set: &[usize]) -> GeometryData {
|
||||
let (tris, order) = bvh.triangles();
|
||||
let vcount = mesh.positions.len();
|
||||
let mut nodes: Vec<[u32; 4]> = Vec::with_capacity(bvh.nodes().len() * 2);
|
||||
for (lo, hi, first, count) in bvh.nodes() {
|
||||
nodes.push(bits(lo, first));
|
||||
nodes.push(bits(hi, count));
|
||||
}
|
||||
let mut out: Vec<[u32; 4]> = Vec::with_capacity(tris.len() * 4);
|
||||
for (t, &orig) in tris.iter().zip(order) {
|
||||
let o = orig as usize;
|
||||
let idx = [0, 1, 2].map(|k| mesh.indices.get(o * 3 + k).copied().filter(|i| (*i as usize) < vcount).unwrap_or(0));
|
||||
let set = tri_set.get(o).copied().filter(|s| *s < MAX_SETS).map_or(u32::MAX, |s| s as u32);
|
||||
let sign: f32 = mesh.tangents.get(idx[0] as usize).map_or(1.0, |t| if t.w < 0.0 { -1.0 } else { 1.0 });
|
||||
out.push(bits(t[0], set));
|
||||
out.push(bits(t[1], sign.to_bits()));
|
||||
out.push(bits(t[2], 0));
|
||||
out.push([idx[0], idx[1], idx[2], 0]);
|
||||
}
|
||||
if out.is_empty() {
|
||||
nodes = vec![bits(Vec3::ZERO, 0), bits(Vec3::ZERO, 1)];
|
||||
out = vec![[0; 4]; 4];
|
||||
}
|
||||
let verts: Vec<[f32; 4]> = (0..vcount.max(1))
|
||||
.flat_map(|v| {
|
||||
let n = mesh.normals.get(v).copied().unwrap_or(Vec3::ZERO);
|
||||
let uv = mesh.uvs.get(v).copied().unwrap_or_default();
|
||||
let t = mesh.tangents.get(v).copied().unwrap_or(Vec4::X);
|
||||
[[n.x, n.y, n.z, uv.x], [t.x, t.y, t.z, uv.y]]
|
||||
})
|
||||
.collect();
|
||||
((nodes, out), verts)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::headless::Headless;
|
||||
use crate::trace::{TraceSet, Tracer};
|
||||
use texturecraft_compose::{BakedMaps, Composite, all_tiles, tile_bytes};
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_geom::{Bvh, primitives};
|
||||
|
||||
fn camera() -> OrbitCamera {
|
||||
let mut cam = OrbitCamera::default();
|
||||
cam.distance = 4.0;
|
||||
cam
|
||||
}
|
||||
|
||||
/// A sphere whose one texture set holds the uniform channel `values`, that set uploaded to
|
||||
/// the headless renderer.
|
||||
fn sphere_scene(h: &mut Headless, env: EnvImage, values: &[(Channel, [f32; 3])]) -> TraceScene {
|
||||
let chans: Vec<Channel> = values.iter().map(|(c, _)| *c).collect();
|
||||
let mut composite = Composite::new(&chans, 64);
|
||||
for (c, v) in values {
|
||||
let raw: Vec<u16> = v[..c.components()].iter().map(|x| texturecraft_texel::to_u16(*x)).collect();
|
||||
let img = composite.channels.get_mut(c).unwrap();
|
||||
for y in 0..64 {
|
||||
for x in 0..64 {
|
||||
img.set(x, y, &raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1);
|
||||
for (tx, ty) in all_tiles(64, 64) {
|
||||
for k in DisplayKind::ALL {
|
||||
h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty));
|
||||
}
|
||||
}
|
||||
let mesh = Arc::new(primitives::sphere(1.0, 32, 16));
|
||||
let bvh = Arc::new(Bvh::new(&mesh));
|
||||
TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0)
|
||||
}
|
||||
|
||||
fn gpu() -> Option<(Headless, GpuTracer)> {
|
||||
let Ok(h) = Headless::new() else {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
return None;
|
||||
};
|
||||
let t = match GpuTracer::new(&h.device) {
|
||||
Ok(t) => t,
|
||||
Err(e) if !GpuTracer::supported(&h.device) => {
|
||||
eprintln!("skipping: {e}");
|
||||
return None;
|
||||
}
|
||||
Err(e) => panic!("{e}"),
|
||||
};
|
||||
Some((h, t))
|
||||
}
|
||||
|
||||
/// The radiance accumulation, read back.
|
||||
fn accumulation(h: &Headless, t: &GpuTracer) -> Vec<[f32; 4]> {
|
||||
let acc = t.acc.as_ref().unwrap();
|
||||
let bytes = acc.width as u64 * acc.height as u64 * 16;
|
||||
let staging = h.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
size: bytes,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut enc = h.device.create_command_encoder(&Default::default());
|
||||
enc.copy_buffer_to_buffer(&acc.acc[0], 0, &staging, 0, bytes);
|
||||
h.queue.submit([enc.finish()]);
|
||||
staging.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
h.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap();
|
||||
bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec()
|
||||
}
|
||||
|
||||
const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])];
|
||||
|
||||
#[test]
|
||||
fn white_furnace_on_the_gpu_stays_bounded_and_finite() {
|
||||
// White spheres in a uniform white environment reflect at most what arrives: at half
|
||||
// exposure the environment shows as 0.5 and the spheres between 0.25 and 0.5.
|
||||
use Channel::*;
|
||||
let Some((mut h, mut t)) = gpu() else { return };
|
||||
let everything = [(CoatWeight, [1.0; 3]), (SheenWeight, [1.0; 3]), (AnisotropyLevel, [1.0; 3]), (ScatterWeight, [1.0; 3])];
|
||||
for (name, extra) in [("white", &[][..]), ("every lobe", &everything[..])] {
|
||||
let values: Vec<_> = WHITE.iter().chain(extra).copied().collect();
|
||||
let env = EnvImage { width: 8, height: 4, data: vec![[1.0; 3]; 32] };
|
||||
let scene = sphere_scene(&mut h, env, &values);
|
||||
let d = TraceDisplay { exposure: 0.5, aces: false, env_opacity: 1.0, denoise: false };
|
||||
let (w, _, px) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &TraceSettings { bounces: 8 }, &d, [64, 48], 256).unwrap();
|
||||
assert!(accumulation(&h, &t).iter().all(|v| v.iter().all(|c| c.is_finite())), "{name}: no NaN or infinity");
|
||||
let at = |x: u32, y: u32| texturecraft_texel::srgb_to_linear(px[((y * w + x) * 4 + 1) as usize] as f32 / 255.0);
|
||||
assert!((at(0, 0) - 0.5).abs() < 0.02, "{name}: background {}", at(0, 0));
|
||||
let block: Vec<f32> = (18..30).flat_map(|y| (26..38).map(move |x| (x, y))).map(|(x, y)| at(x, y)).collect();
|
||||
let mean = block.iter().sum::<f32>() / block.len() as f32;
|
||||
assert!(mean > 0.25 && mean <= 0.5 * 1.05, "{name}: sphere {mean}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_matches_cpu_with_every_lobe_glass_and_lens() {
|
||||
use Channel::*;
|
||||
let Some((mut h, mut t)) = gpu() else { return };
|
||||
let values = [
|
||||
(BaseColor, [0.8, 0.5, 0.3]),
|
||||
(Roughness, [0.35; 3]),
|
||||
(CoatWeight, [0.8; 3]),
|
||||
(CoatRoughness, [0.15; 3]),
|
||||
(SheenWeight, [0.6; 3]),
|
||||
(SheenColor, [0.4, 0.6, 1.0]),
|
||||
(AnisotropyLevel, [0.8; 3]),
|
||||
(AnisotropyAngle, [0.2; 3]),
|
||||
(ScatterWeight, [0.7; 3]),
|
||||
];
|
||||
let glass = [(BaseColor, [0.9, 0.95, 1.0]), (Roughness, [0.2; 3]), (Transmission, [0.9; 3]), (CoatWeight, [0.6; 3]), (CoatNormal, [0.65, 0.5, 0.977])];
|
||||
for (name, values, lens) in [("every lobe", &values[..], None), ("glass under a thin lens", &glass[..], Some([3.2, 0.2]))] {
|
||||
let mut scene = sphere_scene(&mut h, crate::ibl::environment("Studio Contrast", 256), values);
|
||||
(scene.lens, scene.ior) = (lens, 1.45);
|
||||
let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false };
|
||||
let settings = TraceSettings { bounces: 6 };
|
||||
let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap();
|
||||
let mut cpu = Tracer::new(48, 36);
|
||||
for _ in 0..1024 {
|
||||
cpu.pass(&scene, &camera(), &settings);
|
||||
}
|
||||
assert_region_means_match(name, &gpu, &cpu.rgba8(&d), 48, 36, 3.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Mean luminance of each 6×6 block of two RGBA8 renders agrees within `tol` 8-bit levels.
|
||||
fn assert_region_means_match(name: &str, a: &[u8], b: &[u8], w: usize, h: usize, tol: f32) {
|
||||
let lum = |img: &[u8], x: usize, y: usize| {
|
||||
let p = &img[(y * w + x) * 4..(y * w + x) * 4 + 3];
|
||||
0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32
|
||||
};
|
||||
let mut worst = 0.0f32;
|
||||
for by in (0..h).step_by(6) {
|
||||
for bx in (0..w).step_by(6) {
|
||||
let (mut sa, mut sb, mut n) = (0.0, 0.0, 0.0);
|
||||
for y in by..(by + 6).min(h) {
|
||||
for x in bx..(bx + 6).min(w) {
|
||||
sa += lum(a, x, y);
|
||||
sb += lum(b, x, y);
|
||||
n += 1.0;
|
||||
}
|
||||
}
|
||||
worst = worst.max(((sa - sb) / n).abs());
|
||||
}
|
||||
}
|
||||
assert!(worst < tol, "{name}: worst block differs by {worst} levels");
|
||||
}
|
||||
|
||||
/// Samples per second at 1080p on the material ball, GPU against CPU:
|
||||
/// `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture speed`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn speed_at_1080p() {
|
||||
let Some((h, mut t)) = gpu() else { return };
|
||||
let mesh = Arc::new(primitives::material_ball());
|
||||
let (lo, hi) = mesh.bounds();
|
||||
let mut cam = OrbitCamera::default();
|
||||
cam.frame(lo, hi);
|
||||
let scene = TraceScene::new(mesh.clone(), Arc::new(Bvh::new(&mesh)), Vec::new(), Arc::new(crate::ibl::environment("Studio Soft", 1024)), 0.0);
|
||||
let (settings, d) = (TraceSettings::default(), TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.0, denoise: true });
|
||||
let run = |t: &mut GpuTracer, n| t.render(&h.device, &h.queue, &h.renderer, &scene, &cam, &settings, &d, [1920, 1080], n).unwrap();
|
||||
run(&mut t, 8);
|
||||
let t0 = std::time::Instant::now();
|
||||
run(&mut t, 8);
|
||||
let base = t0.elapsed().as_secs_f64();
|
||||
let t0 = std::time::Instant::now();
|
||||
run(&mut t, 520);
|
||||
let gpu = 512.0 / (t0.elapsed().as_secs_f64() - base);
|
||||
let mut cpu_t = Tracer::new(1920, 1080);
|
||||
cpu_t.pass(&scene, &cam, &settings);
|
||||
let t0 = std::time::Instant::now();
|
||||
for _ in 0..16 {
|
||||
cpu_t.pass(&scene, &cam, &settings);
|
||||
}
|
||||
let cpu = 16.0 / t0.elapsed().as_secs_f64();
|
||||
eprintln!("1080p material ball: GPU {gpu:.0} samples/s, CPU {cpu:.1} samples/s, {:.1}x", gpu / cpu);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bvh_depth_counts_levels_and_rejects_cycles() {
|
||||
let leaf = (Vec3::ZERO, Vec3::ONE, 0, 1);
|
||||
let inner = (Vec3::ZERO, Vec3::ONE, 1, 0);
|
||||
assert_eq!(bvh_depth(&[leaf]), Some(1));
|
||||
assert_eq!(bvh_depth(&[inner, leaf, leaf]), Some(2));
|
||||
assert_eq!(bvh_depth(&[(Vec3::ZERO, Vec3::ONE, 0, 0), leaf]), None, "a node that is its own child");
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,17 @@
|
||||
//! overlay, and a [`headless`] device for renders
|
||||
//! without a window. No UI toolkit dependency; the egui shell drives it through
|
||||
//! [`Renderer::prepare`] and [`Renderer::blit`]. Fragment passes only, so it runs on WebGPU and
|
||||
//! WebGL2 too.
|
||||
//! WebGL2 too. Rendering mode's path tracer runs on the CPU ([`trace`]) or, where compute shaders
|
||||
//! exist (not WebGL2), on the GPU ([`gpu_trace`]).
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod gpu_trace;
|
||||
pub mod mesh_maps;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod headless;
|
||||
pub mod ibl;
|
||||
pub mod readback;
|
||||
pub mod renderer;
|
||||
pub mod trace;
|
||||
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Reading RGBA8 textures back to the CPU: blocking (headless renders, screenshots) or without
|
||||
//! stalling (the app polls until the copy is mapped).
|
||||
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
/// A texture copy on its way to the CPU.
|
||||
pub struct Readback {
|
||||
buf: wgpu::Buffer,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Bytes per buffer row (padded to the copy alignment).
|
||||
row: u32,
|
||||
/// Set by the map callback: whether mapping worked.
|
||||
mapped: Arc<Mutex<Option<bool>>>,
|
||||
}
|
||||
|
||||
impl Readback {
|
||||
/// Encode the copy of mip 0 of `texture` (an RGBA8 format) into a mappable buffer.
|
||||
pub fn new(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> Readback {
|
||||
let (width, height) = (texture.width(), texture.height());
|
||||
let row = (width * 4).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
|
||||
let buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("tc_read"),
|
||||
size: u64::from(row) * u64::from(height),
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buf,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(height) },
|
||||
},
|
||||
wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
|
||||
);
|
||||
Readback { buf, width, height, row, mapped: Arc::new(Mutex::new(None)) }
|
||||
}
|
||||
|
||||
/// Start mapping; call once, after the encoder holding the copy was submitted.
|
||||
pub fn map(&self) {
|
||||
let mapped = self.mapped.clone();
|
||||
self.buf.slice(..).map_async(wgpu::MapMode::Read, move |r| *mapped.lock().unwrap_or_else(PoisonError::into_inner) = Some(r.is_ok()));
|
||||
}
|
||||
|
||||
/// The tightly packed pixels once mapped: None while pending, Some(None) when it failed.
|
||||
pub fn take(&self) -> Option<Option<(u32, u32, Vec<u8>)>> {
|
||||
let ok = (*self.mapped.lock().unwrap_or_else(PoisonError::into_inner))?;
|
||||
Some(ok.then(|| self.pixels()).flatten())
|
||||
}
|
||||
|
||||
fn pixels(&self) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let data = self.buf.slice(..).get_mapped_range().ok()?;
|
||||
let line = (self.width * 4) as usize;
|
||||
let mut out = Vec::with_capacity(line * self.height as usize);
|
||||
for y in 0..self.height as usize {
|
||||
let start = y * self.row as usize;
|
||||
out.extend_from_slice(data.get(start..start + line)?);
|
||||
}
|
||||
Some((self.width, self.height, out))
|
||||
}
|
||||
|
||||
/// Copy, submit and wait (the web cannot block: there it returns None).
|
||||
pub fn blocking(device: &wgpu::Device, queue: &wgpu::Queue, texture: &wgpu::Texture) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_read") });
|
||||
let r = Readback::new(device, &mut enc, texture);
|
||||
queue.submit([enc.finish()]);
|
||||
r.map();
|
||||
let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
|
||||
r.take().flatten()
|
||||
}
|
||||
}
|
||||
+254
-48
@@ -3,7 +3,9 @@
|
||||
//! own render pass.
|
||||
//!
|
||||
//! Per view and frame: the scene pass (MSAA, linear HDR premultiplied by scene coverage, resolved)
|
||||
//! → the bloom pyramid (only when bloom is on) → the post pass (flat studio backdrop, exposure,
|
||||
//! → the scene effects (only when on: a G-buffer pass, the screen-space subsurface blur and the
|
||||
//! depth of field, see fx.wgsl) → the bloom pyramid (only when bloom is on) → the post pass (flat
|
||||
//! studio backdrop, exposure,
|
||||
//! tone mapping, effects, sRGB) into the view's RGBA8 target that [`Renderer::blit`] and
|
||||
//! [`Renderer::read_view`] use. The key-light shadow map is re-rendered only when the mesh, the
|
||||
//! light direction or the visible texture sets change.
|
||||
@@ -17,7 +19,7 @@ use std::collections::HashMap;
|
||||
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use texturecraft_compose::{DisplayKind, ImageRes};
|
||||
use texturecraft_core::{DisplaySettings, ToneMapping};
|
||||
use texturecraft_core::{Channel, DisplaySettings, Project, ToneMapping};
|
||||
use texturecraft_geom::glam::{Mat4, Vec3};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_texel::TILE;
|
||||
@@ -39,6 +41,8 @@ const BLOOM_THRESHOLD: f32 = 1.0;
|
||||
const BLOOM_GAIN: f32 = 0.15;
|
||||
/// Frames averaged by idle accumulation (temporal anti-aliasing).
|
||||
pub const TAA_SAMPLES: u32 = 16;
|
||||
/// Largest depth of field blur radius, as a fraction of the view height.
|
||||
const MAX_COC: f32 = 0.03;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
@@ -56,6 +60,7 @@ struct GlobalsRaw {
|
||||
shadow: [f32; 4],
|
||||
material: [f32; 4],
|
||||
scatter: [f32; 4],
|
||||
fwd: [f32; 4],
|
||||
}
|
||||
|
||||
/// The post pass uniform (see `Post` in post.wgsl).
|
||||
@@ -64,6 +69,9 @@ struct GlobalsRaw {
|
||||
struct PostRaw {
|
||||
a: [f32; 4],
|
||||
b: [f32; 4],
|
||||
c: [f32; 4],
|
||||
d: [f32; 4],
|
||||
e: [f32; 4],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
@@ -130,6 +138,15 @@ pub struct Shade {
|
||||
/// Per-channel diffuse wrap where the scattering weight is 1 (0 = plain Lambert), see
|
||||
/// [`scatter_wrap`].
|
||||
pub scatter: [f32; 3],
|
||||
/// Index of refraction of the Transmission channel.
|
||||
pub ior: f32,
|
||||
/// Depth of field (3D material view): focus depth along the view axis (0: the orbit
|
||||
/// target) and lens radius as a fraction of the mesh's bounding radius.
|
||||
pub dof: Option<[f32; 2]>,
|
||||
/// Screen-space subsurface blur of the scattering diffuse light (3D material view): mean
|
||||
/// free path per color channel as a fraction of the mesh's bounding radius. Set by
|
||||
/// [`Shade::from_project`] for projects with a Scattering weight channel.
|
||||
pub sss_blur: Option<[f32; 3]>,
|
||||
}
|
||||
|
||||
/// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the
|
||||
@@ -163,9 +180,19 @@ impl Shade {
|
||||
parallax: d.parallax,
|
||||
taa: d.taa,
|
||||
scatter: scatter_wrap(d),
|
||||
ior: d.ior,
|
||||
dof: d.dof.enabled.then_some([d.dof.focus_distance, d.dof.aperture]),
|
||||
..Shade::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Shade::from_display`] of the project's settings, plus the subsurface blur where a
|
||||
/// texture set has the Scattering weight channel.
|
||||
pub fn from_project(p: &Project) -> Shade {
|
||||
let d = &p.display;
|
||||
let scatters = d.scatter_radius > 0.0 && p.texture_sets.iter().any(|t| t.has_channel(Channel::ScatterWeight));
|
||||
Shade { sss_blur: scatters.then(|| d.scatter_color.map(|c| c.max(0.0) * d.scatter_radius)), ..Shade::from_display(d) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Shade {
|
||||
@@ -194,6 +221,9 @@ impl Default for Shade {
|
||||
parallax: false,
|
||||
taa: false,
|
||||
scatter: scatter_wrap(&DisplaySettings::default()),
|
||||
ior: 1.5,
|
||||
dof: None,
|
||||
sss_blur: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,7 +290,11 @@ impl Tex {
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
// COPY_SRC: the GPU path tracer copies the display textures into its arrays.
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_DST
|
||||
| wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
@@ -294,6 +328,21 @@ struct MeshGpu {
|
||||
radius: f32,
|
||||
}
|
||||
|
||||
/// The scene effect targets of a view (full resolution unless noted), created the first time
|
||||
/// depth of field or the subsurface blur is used.
|
||||
struct Fx {
|
||||
/// G-buffer: scattering diffuse light, view depth (see `fs_gbuf`), and its depth buffer.
|
||||
gbuf: wgpu::TextureView,
|
||||
gbuf_depth: wgpu::TextureView,
|
||||
/// The horizontal subsurface pass, then the depth of field result.
|
||||
a: wgpu::TextureView,
|
||||
/// The scene with the subsurface blur.
|
||||
b: wgpu::TextureView,
|
||||
/// Half resolution: the gathered blur and the near-field coverage.
|
||||
half: wgpu::TextureView,
|
||||
near: wgpu::TextureView,
|
||||
}
|
||||
|
||||
/// The bloom pyramid of a view, created the first time bloom is used.
|
||||
struct Bloom {
|
||||
/// 1/2, 1/4, ... resolution targets.
|
||||
@@ -326,6 +375,7 @@ struct ViewTargets {
|
||||
post_buf: wgpu::Buffer,
|
||||
post_bg: wgpu::BindGroup,
|
||||
bloom: Option<Bloom>,
|
||||
fx: Option<Fx>,
|
||||
blit_buf: wgpu::Buffer,
|
||||
blit_bg: wgpu::BindGroup,
|
||||
/// Set by [`Renderer::prepare`]: the view has content to blit.
|
||||
@@ -363,6 +413,12 @@ pub struct Renderer {
|
||||
post_pipeline: wgpu::RenderPipeline,
|
||||
/// Bright pass + first downsample, downsample, additive upsample.
|
||||
bloom_pipelines: [wgpu::RenderPipeline; 3],
|
||||
/// The G-buffer of the scene effects (`fs_gbuf`).
|
||||
gbuf_pipeline: wgpu::RenderPipeline,
|
||||
/// Subsurface blur (horizontal, vertical), depth of field gather and composite (fx.wgsl).
|
||||
sss_pipelines: [wgpu::RenderPipeline; 2],
|
||||
dof_gather_pipeline: wgpu::RenderPipeline,
|
||||
dof_pipeline: wgpu::RenderPipeline,
|
||||
shadow_pipeline: wgpu::RenderPipeline,
|
||||
mip_pipelines: HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>,
|
||||
util_module: wgpu::ShaderModule,
|
||||
@@ -416,10 +472,10 @@ fn uniform_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
|
||||
}
|
||||
}
|
||||
|
||||
fn display_format(k: DisplayKind) -> wgpu::TextureFormat {
|
||||
pub(crate) fn display_format(k: DisplayKind) -> wgpu::TextureFormat {
|
||||
match k {
|
||||
DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
DisplayKind::Orm | DisplayKind::Normal | DisplayKind::Lobes => wgpu::TextureFormat::Rgba8Unorm,
|
||||
DisplayKind::Orm | DisplayKind::Normal | DisplayKind::Lobes | DisplayKind::Extra => wgpu::TextureFormat::Rgba8Unorm,
|
||||
DisplayKind::Height => wgpu::TextureFormat::Rgba16Float,
|
||||
}
|
||||
}
|
||||
@@ -427,7 +483,7 @@ fn display_format(k: DisplayKind) -> wgpu::TextureFormat {
|
||||
/// Textures of the optional lobe channels: most sets never use them, so they cost no memory or
|
||||
/// bandwidth (a 1×1 neutral texture) until painted.
|
||||
fn lazy(k: DisplayKind) -> bool {
|
||||
matches!(k, DisplayKind::Lobes | DisplayKind::Sheen)
|
||||
matches!(k, DisplayKind::Lobes | DisplayKind::Sheen | DisplayKind::Extra)
|
||||
}
|
||||
|
||||
/// A `w × h` texture filled with `texel`.
|
||||
@@ -586,7 +642,7 @@ impl Renderer {
|
||||
let shader = |label: &str, source: &str| device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) });
|
||||
let module = shader("tc_mesh", include_str!("shaders/mesh.wgsl"));
|
||||
let util_module = shader("tc_util", include_str!("shaders/util.wgsl"));
|
||||
let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl")));
|
||||
let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl")));
|
||||
let shadow_module = shader("tc_shadow", include_str!("shaders/shadow.wgsl"));
|
||||
let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries });
|
||||
let globals_bgl = bgl(
|
||||
@@ -605,7 +661,7 @@ impl Renderer {
|
||||
let set_bgl = bgl("tc_set", &set_entries);
|
||||
let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]);
|
||||
let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]);
|
||||
let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4)]);
|
||||
let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]);
|
||||
let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]);
|
||||
let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| {
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 })
|
||||
@@ -636,6 +692,26 @@ impl Renderer {
|
||||
let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None);
|
||||
let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))]
|
||||
.map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None));
|
||||
let gbuf_pipeline = pipeline(device, "tc_gbuf", &layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less)));
|
||||
let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None));
|
||||
let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None);
|
||||
let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL });
|
||||
let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("tc_dof_gather"),
|
||||
layout: Some(&fx_layout),
|
||||
vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() },
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &post_module,
|
||||
entry_point: Some("fs_dof_gather"),
|
||||
targets: &[dof_target.clone(), dof_target],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let shadow_depth = wgpu::DepthStencilState {
|
||||
bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 },
|
||||
..depth_state(true, wgpu::CompareFunction::Less)
|
||||
@@ -709,6 +785,10 @@ impl Renderer {
|
||||
blit_pipeline,
|
||||
post_pipeline,
|
||||
bloom_pipelines,
|
||||
gbuf_pipeline,
|
||||
sss_pipelines,
|
||||
dof_gather_pipeline,
|
||||
dof_pipeline,
|
||||
shadow_pipeline,
|
||||
accum_pipeline,
|
||||
mip_pipelines: HashMap::new(),
|
||||
@@ -736,6 +816,17 @@ impl Renderer {
|
||||
&self.env_name
|
||||
}
|
||||
|
||||
/// Each texture set's display textures in [`DisplayKind::ALL`] order (lazy kinds may still be
|
||||
/// 1×1 placeholders), for the GPU path tracer.
|
||||
pub fn display_textures(&self) -> Vec<Vec<&wgpu::Texture>> {
|
||||
self.sets.iter().map(|s| s.tex.iter().take(DisplayKind::ALL.len()).map(|t| &t.texture).collect()).collect()
|
||||
}
|
||||
|
||||
/// Changes whenever what the views show changes (uploads, mesh, environment).
|
||||
pub fn content_rev(&self) -> u64 {
|
||||
self.content_rev
|
||||
}
|
||||
|
||||
/// Use environment `name`: with `image`, that equirect image (an imported `.hdr`/`.exr`, or
|
||||
/// any image, linearized), prefiltered on the CPU (rayon); otherwise the built-in of that
|
||||
/// name (no-op when already current; unknown names give the default studio).
|
||||
@@ -978,8 +1069,10 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Effect bind group (`fx_bgl`): source texture, the post uniform, an extra texture.
|
||||
fn fx_bind_group(&self, device: &wgpu::Device, src: &wgpu::TextureView, aux: &wgpu::TextureView, post: &wgpu::Buffer) -> wgpu::BindGroup {
|
||||
/// Effect bind group (`fx_bgl`): source texture, the post uniform, up to three extra
|
||||
/// textures (`fx_a`, `fx_b`, `fx_c`; missing ones read black).
|
||||
fn fx_bind_group(&self, device: &wgpu::Device, src: &wgpu::TextureView, extra: &[&wgpu::TextureView], post: &wgpu::Buffer) -> wgpu::BindGroup {
|
||||
let tex = |i: usize| wgpu::BindingResource::TextureView(extra.get(i).copied().unwrap_or(&self.black));
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("tc_fx"),
|
||||
layout: &self.fx_bgl,
|
||||
@@ -987,7 +1080,9 @@ impl Renderer {
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: post.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(aux) },
|
||||
wgpu::BindGroupEntry { binding: 4, resource: tex(0) },
|
||||
wgpu::BindGroupEntry { binding: 5, resource: tex(1) },
|
||||
wgpu::BindGroupEntry { binding: 6, resource: tex(2) },
|
||||
],
|
||||
})
|
||||
}
|
||||
@@ -1029,7 +1124,7 @@ impl Renderer {
|
||||
size,
|
||||
msaa: target_view(device, "tc_msaa", size, self.hdr_format, MSAA),
|
||||
depth: target_view(device, "tc_depth", size, DEPTH_FORMAT, MSAA),
|
||||
post_bg: self.fx_bind_group(device, &accum, &self.black, &post_buf),
|
||||
post_bg: self.fx_bind_group(device, &accum, &[], &post_buf),
|
||||
hdr,
|
||||
accum,
|
||||
accum_bg,
|
||||
@@ -1041,6 +1136,7 @@ impl Renderer {
|
||||
globals_bg: None,
|
||||
post_buf,
|
||||
bloom: None,
|
||||
fx: None,
|
||||
blit_buf,
|
||||
blit_bg,
|
||||
ready: false,
|
||||
@@ -1051,19 +1147,36 @@ impl Renderer {
|
||||
fn create_bloom(&self, device: &wgpu::Device, v: &ViewTargets) -> (Bloom, wgpu::BindGroup) {
|
||||
let levels: Vec<wgpu::TextureView> =
|
||||
(1..=BLOOM_LEVELS).map(|i| target_view(device, "tc_bloom", [(v.size[0] >> i).max(1), (v.size[1] >> i).max(1)], self.hdr_format, 1)).collect();
|
||||
let fx = |src: &wgpu::TextureView| self.fx_bind_group(device, src, &self.black, &v.post_buf);
|
||||
let fx = |src: &wgpu::TextureView| self.fx_bind_group(device, src, &[], &v.post_buf);
|
||||
let down = std::iter::once(&v.accum).chain(&levels).take(levels.len()).map(fx).collect();
|
||||
let up = levels.iter().skip(1).map(fx).collect();
|
||||
let post_bg = self.fx_bind_group(device, &v.accum, levels.first().unwrap_or(&self.black), &v.post_buf);
|
||||
let post_bg = self.fx_bind_group(device, &v.accum, &levels.iter().take(1).collect::<Vec<_>>(), &v.post_buf);
|
||||
(Bloom { levels, down, up }, post_bg)
|
||||
}
|
||||
|
||||
fn targets(&mut self, device: &wgpu::Device, id: u64, size: [u32; 2], bloom: bool) -> Option<&mut ViewTargets> {
|
||||
fn create_fx(&self, device: &wgpu::Device, size: [u32; 2]) -> Fx {
|
||||
let full = |label| target_view(device, label, size, self.hdr_format, 1);
|
||||
let half_size = [(size[0] / 2).max(1), (size[1] / 2).max(1)];
|
||||
Fx {
|
||||
gbuf: full("tc_gbuf"),
|
||||
gbuf_depth: target_view(device, "tc_gbuf_depth", size, DEPTH_FORMAT, 1),
|
||||
a: full("tc_fx_a"),
|
||||
b: full("tc_fx_b"),
|
||||
half: target_view(device, "tc_dof_half", half_size, self.hdr_format, 1),
|
||||
near: target_view(device, "tc_dof_near", half_size, self.hdr_format, 1),
|
||||
}
|
||||
}
|
||||
|
||||
fn targets(&mut self, device: &wgpu::Device, id: u64, size: [u32; 2], bloom: bool, fx: bool) -> Option<&mut ViewTargets> {
|
||||
let size = [size[0].clamp(1, 8192), size[1].clamp(1, 8192)];
|
||||
if self.views.get(&id).is_none_or(|v| v.size != size) {
|
||||
let v = self.create_targets(device, size);
|
||||
self.views.insert(id, v);
|
||||
}
|
||||
if fx && self.views.get(&id).is_some_and(|v| v.fx.is_none()) {
|
||||
let f = self.create_fx(device, size);
|
||||
self.views.get_mut(&id)?.fx = Some(f);
|
||||
}
|
||||
if bloom
|
||||
&& let Some(v) = self.views.get(&id)
|
||||
&& v.bloom.is_none()
|
||||
@@ -1206,6 +1319,23 @@ impl Renderer {
|
||||
// ray grid would show a single flat environment color).
|
||||
let bg_vp = OrbitCamera { ortho: false, ..frame.camera }.view_proj(aspect);
|
||||
let e = frame.camera.eye();
|
||||
// Scene effects (3D material view; they need float targets for depths and signed light).
|
||||
let scene_fx = !data && frame.kind == ViewKind::Scene && self.hdr_format == HDR_FORMAT && self.mesh.is_some();
|
||||
let dof = s.dof.filter(|_| scene_fx);
|
||||
let sss = s.sss_blur.filter(|m| scene_fx && m.iter().any(|v| *v > 0.0));
|
||||
let fx_on = dof.is_some() || sss.is_some();
|
||||
let cam = &frame.camera;
|
||||
let half_h = (cam.fov.clamp(5.0, 150.0).to_radians() * 0.5).tan();
|
||||
let height = frame.size[1].max(1) as f32;
|
||||
// Pixels per world unit at view depth z: k / z in perspective, k in orthographic views.
|
||||
let k = if cam.ortho { height / (2.0 * cam.distance.max(1e-6) * half_h) } else { height / (2.0 * half_h) };
|
||||
let ppw = |z: f32| if cam.ortho { k } else { k / z.max(1e-6) };
|
||||
let dof_c = dof.map_or([0.0; 4], |[focus, aperture]| {
|
||||
let f = if focus > 0.0 { focus } else { cam.distance };
|
||||
[aperture.max(0.0) * radius * ppw(f), f, MAX_COC * height, sample as f32]
|
||||
});
|
||||
let sss_d = sss.map_or([0.0; 4], |m| [m[0] * radius, m[1] * radius, m[2] * radius, k]);
|
||||
let fwd = cam.forward();
|
||||
let raw = GlobalsRaw {
|
||||
view_proj: vp.to_cols_array_2d(),
|
||||
inv_view_proj: bg_vp.inverse().to_cols_array_2d(),
|
||||
@@ -1219,15 +1349,19 @@ impl Renderer {
|
||||
light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(),
|
||||
// Normal offset: 1.5 shadow texels of the light frustum (2 × radius wide).
|
||||
shadow: [if shadow_vp.is_some() { 1.0 } else { 0.0 }, 1.0 / SHADOW_SIZE as f32, radius * 3.0 / SHADOW_SIZE as f32, 0.0],
|
||||
material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, 0.0],
|
||||
scatter: [s.scatter[0], s.scatter[1], s.scatter[2], 0.0],
|
||||
material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior],
|
||||
scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }],
|
||||
fwd: [fwd.x, fwd.y, fwd.z, 0.0],
|
||||
};
|
||||
let flag = |b: bool| if b { 1.0 } else { 0.0 };
|
||||
let post = PostRaw {
|
||||
a: [2f32.powf(s.exposure_ev), flag(s.aces), flag(data), fx(s.bloom) * BLOOM_GAIN],
|
||||
b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD],
|
||||
c: dof_c,
|
||||
d: sss_d,
|
||||
e: [flag(cam.ortho), 0.0, 0.0, 0.0],
|
||||
};
|
||||
let Some(v) = self.targets(device, frame.view_id, frame.size, bloom) else { return };
|
||||
let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on) else { return };
|
||||
queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw));
|
||||
queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post));
|
||||
v.ready = true;
|
||||
@@ -1235,11 +1369,32 @@ impl Renderer {
|
||||
v.samples = sample;
|
||||
let Some(v) = self.views.get(&frame.view_id) else { return };
|
||||
let Some(globals_bg) = v.globals_bg.as_ref() else { return };
|
||||
if sample == 0 {
|
||||
self.scene_pass(encoder, v, &v.accum, globals_bg, frame);
|
||||
} else {
|
||||
self.scene_pass(encoder, v, &v.hdr, globals_bg, frame);
|
||||
fullscreen_blend(encoder, "tc_accum", &v.accum, wgpu::LoadOp::Load, &self.accum_pipeline, &v.accum_bg, 1.0 / f64::from(sample + 1));
|
||||
let weight = 1.0 / f64::from(sample + 1);
|
||||
match v.fx.as_ref().filter(|_| fx_on) {
|
||||
// The effects run on every frame before it joins the average, so idle accumulation
|
||||
// also smooths the depth of field's sampling pattern (turned each frame). Their
|
||||
// G-buffer (unjittered) stays valid while the view accumulates.
|
||||
Some(f) => {
|
||||
self.scene_pass(encoder, v, &v.hdr, globals_bg, frame);
|
||||
if sample == 0 {
|
||||
self.gbuf_pass(encoder, f, globals_bg, frame);
|
||||
}
|
||||
let out = self.scene_fx(device, encoder, v, f, sss.is_some(), dof.is_some());
|
||||
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("tc_accum_fx"),
|
||||
layout: &self.mip_bgl,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(out) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
|
||||
],
|
||||
});
|
||||
fullscreen_blend(encoder, "tc_accum", &v.accum, wgpu::LoadOp::Load, &self.accum_pipeline, &bg, weight);
|
||||
}
|
||||
None if sample == 0 => self.scene_pass(encoder, v, &v.accum, globals_bg, frame),
|
||||
None => {
|
||||
self.scene_pass(encoder, v, &v.hdr, globals_bg, frame);
|
||||
fullscreen_blend(encoder, "tc_accum", &v.accum, wgpu::LoadOp::Load, &self.accum_pipeline, &v.accum_bg, weight);
|
||||
}
|
||||
}
|
||||
if bloom && let Some(b) = &v.bloom {
|
||||
let [pre, down, up] = &self.bloom_pipelines;
|
||||
@@ -1253,6 +1408,81 @@ impl Renderer {
|
||||
fullscreen(encoder, "tc_post", &v.resolve_view, CLEAR, &self.post_pipeline, &v.post_bg);
|
||||
}
|
||||
|
||||
/// The scene effects' G-buffer: the mesh again, single-sampled, into `f.gbuf`.
|
||||
fn gbuf_pass(&self, encoder: &mut wgpu::CommandEncoder, f: &Fx, globals_bg: &wgpu::BindGroup, frame: &Frame) {
|
||||
let Some(m) = &self.mesh else { return };
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("tc_gbuf"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &f.gbuf,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Store },
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &f.gbuf_depth,
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(&self.gbuf_pipeline);
|
||||
pass.set_bind_group(0, globals_bg, &[]);
|
||||
pass.set_vertex_buffer(0, m.vb.slice(..));
|
||||
pass.set_index_buffer(m.ib.slice(..), wgpu::IndexFormat::Uint32);
|
||||
for (range, set) in self.drawable(&m.draws, &frame.visible, None) {
|
||||
pass.set_bind_group(1, &set.bind_group, &[]);
|
||||
pass.draw_indexed(range, 0, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Subsurface blur and depth of field over this frame's scene (`v.hdr`); returns the result.
|
||||
fn scene_fx<'a>(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
v: &'a ViewTargets,
|
||||
f: &'a Fx,
|
||||
sss: bool,
|
||||
dof: bool,
|
||||
) -> &'a wgpu::TextureView {
|
||||
let bg = |src: &wgpu::TextureView, extra: &[&wgpu::TextureView]| self.fx_bind_group(device, src, extra, &v.post_buf);
|
||||
let mut scene = &v.hdr;
|
||||
if sss {
|
||||
let [h, vert] = &self.sss_pipelines;
|
||||
fullscreen(encoder, "tc_sss_h", &f.a, CLEAR, h, &bg(&f.gbuf, &[]));
|
||||
fullscreen(encoder, "tc_sss_v", &f.b, CLEAR, vert, &bg(&f.a, &[&v.hdr]));
|
||||
scene = &f.b;
|
||||
}
|
||||
if dof {
|
||||
let target = |view| {
|
||||
Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Store },
|
||||
})
|
||||
};
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("tc_dof_gather"),
|
||||
color_attachments: &[target(&f.half), target(&f.near)],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(&self.dof_gather_pipeline);
|
||||
pass.set_bind_group(0, &bg(scene, &[&f.gbuf]), &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
drop(pass);
|
||||
fullscreen(encoder, "tc_dof", &f.a, CLEAR, &self.dof_pipeline, &bg(scene, &[&f.half, &f.gbuf, &f.near]));
|
||||
scene = &f.a;
|
||||
}
|
||||
scene
|
||||
}
|
||||
|
||||
/// Background, mesh and wireframe into the view's MSAA HDR target, resolved to `resolve`.
|
||||
fn scene_pass(&self, encoder: &mut wgpu::CommandEncoder, v: &ViewTargets, resolve: &wgpu::TextureView, globals_bg: &wgpu::BindGroup, frame: &Frame) {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
@@ -1325,31 +1555,7 @@ impl Renderer {
|
||||
|
||||
/// Read back the rendered view as tightly packed RGBA8 (sRGB-encoded), blocking.
|
||||
pub fn read_view(&self, device: &wgpu::Device, queue: &wgpu::Queue, id: u64) -> Option<(u32, u32, Vec<u8>)> {
|
||||
let v = self.views.get(&id)?;
|
||||
let (w, h) = (v.size[0], v.size[1]);
|
||||
let row = (w * 4).next_multiple_of(256);
|
||||
let buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("tc_read"),
|
||||
size: (row * h) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_read") });
|
||||
enc.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: &v.resolve, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(h) } },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
queue.submit([enc.finish()]);
|
||||
buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
|
||||
let data = buf.slice(..).get_mapped_range().ok()?;
|
||||
let mut out = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h as usize {
|
||||
let start = y * row as usize;
|
||||
out.extend_from_slice(data.get(start..start + (w * 4) as usize)?);
|
||||
}
|
||||
Some((w, h, out))
|
||||
crate::readback::Readback::blocking(device, queue, &self.views.get(&id)?.resolve)
|
||||
}
|
||||
|
||||
/// Forget a view's targets (e.g. a closed panel).
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Scene effects between the scene pass and the post pass, appended to util.wgsl and post.wgsl
|
||||
// (uses `src`, `src_samp`, `post`, `fx_a`): the screen-space subsurface blur and depth of field.
|
||||
// Both read the G-buffer of `fs_gbuf` (mesh.wgsl): rgb the scattering part of the diffuse light,
|
||||
// a the view depth (0: background). Colors are linear HDR premultiplied by scene coverage.
|
||||
|
||||
@group(0) @binding(5) var fx_b: texture_2d<f32>;
|
||||
@group(0) @binding(6) var fx_c: texture_2d<f32>;
|
||||
|
||||
// The texel of `t` under `uv` (no filtering: depths must not blend across silhouettes).
|
||||
fn texel(t: texture_2d<f32>, uv: vec2<f32>) -> vec4<f32> {
|
||||
let d = vec2<i32>(textureDimensions(t));
|
||||
return textureLoad(t, clamp(vec2<i32>(uv * vec2<f32>(d)), vec2<i32>(0), d - 1), 0);
|
||||
}
|
||||
|
||||
// ---- Subsurface scattering: a separable bilateral blur (Jimenez et al., "Separable Subsurface
|
||||
// Scattering", 2015) of the scattering diffuse light, a Gaussian per color channel as wide as
|
||||
// its mean free path, cut off across depth discontinuities.
|
||||
|
||||
const SSS_TAPS: i32 = 8;
|
||||
|
||||
fn px_per_world(z: f32) -> f32 {
|
||||
return select(post.d.w / max(z, 1e-4), post.d.w, post.e.x > 0.5);
|
||||
}
|
||||
|
||||
// One direction of the blur over `src` (rgb light, a depth).
|
||||
fn sss_blur(uv: vec2<f32>, dir: vec2<f32>) -> vec4<f32> {
|
||||
let c = texel(src, uv);
|
||||
let sigma = post.d.xyz * px_per_world(c.a);
|
||||
let smax = max(sigma.r, max(sigma.g, sigma.b));
|
||||
if (c.a <= 0.0 || smax < 0.5) {
|
||||
return c;
|
||||
}
|
||||
let stride = dir / vec2<f32>(textureDimensions(src)) * (smax * 3.0 / f32(SSS_TAPS));
|
||||
let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z));
|
||||
let inv = 1.0 / (2.0 * sigma * sigma + vec3<f32>(1e-4));
|
||||
var sum = c.rgb;
|
||||
var wsum = vec3<f32>(1.0);
|
||||
for (var k = -SSS_TAPS; k <= SSS_TAPS; k++) {
|
||||
if (k == 0) {
|
||||
continue;
|
||||
}
|
||||
let t = texel(src, uv + stride * f32(k));
|
||||
let x = f32(k) * smax * 3.0 / f32(SSS_TAPS);
|
||||
let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0);
|
||||
let w = exp(-x * x * inv) * wd;
|
||||
sum += t.rgb * w;
|
||||
wsum += w;
|
||||
}
|
||||
return vec4<f32>(sum / wsum, c.a);
|
||||
}
|
||||
|
||||
// src: the G-buffer.
|
||||
@fragment
|
||||
fn fs_sss_h(i: FsOut) -> @location(0) vec4<f32> {
|
||||
return sss_blur(i.uv, vec2<f32>(1.0, 0.0));
|
||||
}
|
||||
|
||||
// src: the horizontal pass, fx_a: the scene (without its scattering light, see `fs_mesh`). Adds
|
||||
// the blurred scattering light.
|
||||
@fragment
|
||||
fn fs_sss_v(i: FsOut) -> @location(0) vec4<f32> {
|
||||
let blurred = sss_blur(i.uv, vec2<f32>(0.0, 1.0)).rgb;
|
||||
let scene = textureSampleLevel(fx_a, src_samp, i.uv, 0.0);
|
||||
return scene + vec4<f32>(blurred * clamp(scene.a, 0.0, 1.0), 0.0);
|
||||
}
|
||||
|
||||
// ---- Depth of field: a thin lens. Scatter-as-gather over a golden-angle spiral at half
|
||||
// resolution (after D. Gustafsson, "Bokeh depth of field in a single pass", 2018): a tap counts
|
||||
// where its own circle of confusion reaches the pixel; taps behind the pixel spread at most twice
|
||||
// its own blur (no background bleeding over a sharp foreground), taps in front spread fully (a
|
||||
// blurred foreground covers the sharp background). The full-resolution composite keeps the
|
||||
// sharp scene where the pixel is in focus and nothing blurred covers it.
|
||||
|
||||
const DOF_TAPS: i32 = 48;
|
||||
const GOLDEN_ANGLE: f32 = 2.39996323;
|
||||
|
||||
// Signed circle of confusion radius in full-resolution pixels (negative in front of the focus).
|
||||
fn coc(z: f32) -> f32 {
|
||||
var c = post.c.x;
|
||||
if (z > 0.0) {
|
||||
c = post.c.x * (z - post.c.y) / z;
|
||||
}
|
||||
return clamp(c, -post.c.z, post.c.z);
|
||||
}
|
||||
|
||||
struct DofOut {
|
||||
@location(0) color: vec4<f32>,
|
||||
// How much blurred foreground covers the pixel (r).
|
||||
@location(1) near: vec4<f32>,
|
||||
};
|
||||
|
||||
// src: the scene (full resolution), fx_a: the G-buffer.
|
||||
@fragment
|
||||
fn fs_dof_gather(i: FsOut) -> DofOut {
|
||||
let px = 1.0 / vec2<f32>(textureDimensions(src));
|
||||
let zc = texel(fx_a, i.uv).a;
|
||||
let cc = abs(coc(zc));
|
||||
let rmax = post.c.z;
|
||||
// Half the spacing of the taps: the soft edge of each tap's reach.
|
||||
let h = max(rmax * sqrt(PI_FX / f32(DOF_TAPS)) * 0.5, 0.5);
|
||||
var acc = textureSampleLevel(src, src_samp, i.uv, 0.0);
|
||||
var tot = 1.0;
|
||||
var near = 0.0;
|
||||
// The spiral turns per pixel (interleaved gradient noise) and per accumulated frame, so the
|
||||
// taps' pattern averages into smooth discs instead of showing as dots in bright highlights.
|
||||
let ign = fract(52.9829189 * fract(dot(i.pos.xy, vec2<f32>(0.06711056, 0.00583715))));
|
||||
let turn = (ign + post.c.w * 0.618034) * 6.2831853;
|
||||
for (var k = 0; k < DOF_TAPS; k++) {
|
||||
let r = rmax * sqrt((f32(k) + 0.5) / f32(DOF_TAPS));
|
||||
let a = f32(k) * GOLDEN_ANGLE + turn;
|
||||
let uv = i.uv + vec2<f32>(cos(a), sin(a)) * (r * px);
|
||||
let z = texel(fx_a, uv).a;
|
||||
let nearer = z > 0.0 && (zc <= 0.0 || z < zc);
|
||||
var size = abs(coc(z));
|
||||
if (!nearer) {
|
||||
size = min(size, cc * 2.0);
|
||||
}
|
||||
let m = smoothstep(r - h, r + h, size);
|
||||
acc += mix(acc / tot, textureSampleLevel(src, src_samp, uv, 0.0), m);
|
||||
tot += 1.0;
|
||||
if (nearer) {
|
||||
near = max(near, m * smoothstep(0.5, 1.5, size));
|
||||
}
|
||||
}
|
||||
return DofOut(acc / tot, vec4<f32>(near));
|
||||
}
|
||||
|
||||
const PI_FX: f32 = 3.14159265;
|
||||
|
||||
// src: the sharp scene, fx_a: the gathered blur, fx_b: the G-buffer, fx_c: the near coverage.
|
||||
@fragment
|
||||
fn fs_dof(i: FsOut) -> @location(0) vec4<f32> {
|
||||
let sharp = textureSampleLevel(src, src_samp, i.uv, 0.0);
|
||||
let blur = textureSampleLevel(fx_a, src_samp, i.uv, 0.0);
|
||||
let f = max(smoothstep(0.5, 1.5, abs(coc(texel(fx_b, i.uv).a))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r);
|
||||
return mix(sharp, blur, f);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// TextureCraft viewport shaders: metal/roughness (or specular/glossiness) PBR with image-based
|
||||
// lighting and optional parallax occlusion mapping, plus the optional lobes of the extra channels
|
||||
// (clear coat, sheen, anisotropy, subsurface scattering; packing in compose/src/display.rs), the
|
||||
// (clear coat with its own normal, sheen, anisotropy, subsurface scattering, transmission; packing
|
||||
// in compose/src/display.rs), the G-buffer of the depth of field and subsurface blur passes, the
|
||||
// 2D UV view,
|
||||
// the background, debug views and the 3D wireframe. Output is scene-linear HDR, premultiplied by
|
||||
// alpha = scene coverage over the flat studio backdrop; exposure, tone mapping and sRGB encoding
|
||||
@@ -18,8 +19,9 @@ struct Globals {
|
||||
light: vec4<f32>, // xyz world direction to the key light (rotated with the environment), w intensity (0 = off)
|
||||
light_vp: mat4x4<f32>, // world -> shadow map clip space
|
||||
shadow: vec4<f32>, // x shadows on (1), y shadow map texel (uv), z normal offset (world units), w -
|
||||
material: vec4<f32>, // x specular/glossiness shading (1), y parallax occlusion (1), z accumulation sample index, w -
|
||||
scatter: vec4<f32>, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w -
|
||||
material: vec4<f32>, // x specular/glossiness shading (1), y parallax occlusion (1), z accumulation sample index, w IOR of transmission
|
||||
scatter: vec4<f32>, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1)
|
||||
fwd: vec4<f32>, // xyz camera view direction (unit), w -
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> g: Globals;
|
||||
@@ -35,8 +37,9 @@ struct Globals {
|
||||
@group(1) @binding(4) var t_emis: texture_2d<f32>;
|
||||
@group(1) @binding(5) var t_lobes: texture_2d<f32>;
|
||||
@group(1) @binding(6) var t_sheen: texture_2d<f32>;
|
||||
@group(1) @binding(7) var t_aux: texture_2d<f32>;
|
||||
@group(1) @binding(8) var samp: sampler;
|
||||
@group(1) @binding(7) var t_extra: texture_2d<f32>;
|
||||
@group(1) @binding(8) var t_aux: texture_2d<f32>;
|
||||
@group(1) @binding(9) var samp: sampler;
|
||||
|
||||
struct VIn {
|
||||
@location(0) pos: vec3<f32>,
|
||||
@@ -230,9 +233,23 @@ fn rnm(base: vec3<f32>, detail: vec3<f32>) -> vec3<f32> {
|
||||
return normalize(t * dot(t, u) - u * t.z);
|
||||
}
|
||||
|
||||
// Channel views of the extra lobes (`Channel::ALL` indices 11..18).
|
||||
fn lobe_view(ch: i32, lobes: vec4<f32>, sheen: vec4<f32>, sheen_rough: f32, scatter: f32) -> vec4<f32> {
|
||||
// Signed values packed in 8 bits: byte 128 decodes to exactly 0, so flat normals stay flat
|
||||
// (the CPU packing and both path tracers use the same rule).
|
||||
fn snorm8(v: vec3<f32>) -> vec3<f32> {
|
||||
return clamp((v * 255.0 - 128.0) / 127.0, vec3<f32>(-1.0), vec3<f32>(1.0));
|
||||
}
|
||||
|
||||
// Coat normal (tangent space around the mesh normal) from the Extra texture's signed bytes.
|
||||
fn coat_normal_ts(extra: vec4<f32>) -> vec3<f32> {
|
||||
let xy = snorm8(extra.rgb).xy;
|
||||
return vec3<f32>(xy, sqrt(max(1.0 - dot(xy, xy), 0.0)));
|
||||
}
|
||||
|
||||
// Channel views of the extra lobes (`Channel::ALL` indices 11..20).
|
||||
fn lobe_view(ch: i32, lobes: vec4<f32>, sheen: vec4<f32>, sheen_rough: f32, scatter: f32, extra: vec4<f32>) -> vec4<f32> {
|
||||
switch ch {
|
||||
case 19: { return raw_out(vec3<f32>(extra.b)); }
|
||||
case 20: { return raw_out(coat_normal_ts(extra) * 0.5 + 0.5); }
|
||||
case 11: { return raw_out(vec3<f32>(lobes.r)); }
|
||||
case 12: { return raw_out(vec3<f32>(lobes.g)); }
|
||||
case 13: { return raw_out(vec3<f32>(sheen.a)); }
|
||||
@@ -281,8 +298,41 @@ fn parallax_uv(uv: vec2<f32>, v_ts: vec3<f32>) -> vec2<f32> {
|
||||
return uv + shift * hit;
|
||||
}
|
||||
|
||||
// The shaded color, and the scattering part of its diffuse light (blurred by the subsurface pass).
|
||||
struct Shaded {
|
||||
color: vec4<f32>,
|
||||
sss: vec3<f32>,
|
||||
};
|
||||
|
||||
fn unlit(c: vec4<f32>) -> Shaded {
|
||||
return Shaded(c, vec3<f32>(0.0));
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
|
||||
let o = shade_mesh(i, front);
|
||||
if (g.scatter.w > 0.5) {
|
||||
// The subsurface blur pass adds the scattering light back, blurred (fx.wgsl).
|
||||
return o.color - vec4<f32>(o.sss, 0.0);
|
||||
}
|
||||
return o.color;
|
||||
}
|
||||
|
||||
// The depth of field / subsurface G-buffer: rgb the scattering diffuse light (when the blur is
|
||||
// on), a the view depth (the clear value 0 marks the background).
|
||||
@fragment
|
||||
fn fs_gbuf(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
|
||||
let z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4);
|
||||
var sss = vec3<f32>(0.0);
|
||||
if (g.scatter.w > 0.5) {
|
||||
sss = shade_mesh(i, front).sss;
|
||||
} else if (textureSample(t_base, samp, i.uv).a < hash12(i.clip.xy)) {
|
||||
discard;
|
||||
}
|
||||
return vec4<f32>(sss, z);
|
||||
}
|
||||
|
||||
fn shade_mesh(i: VOut, front: bool) -> Shaded {
|
||||
var n_geo = normalize(i.nrm);
|
||||
if (!front) {
|
||||
n_geo = -n_geo;
|
||||
@@ -302,6 +352,7 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
let emis = emis_t.rgb;
|
||||
let lobes = textureSample(t_lobes, samp, uv);
|
||||
let sheen_t = textureSample(t_sheen, samp, uv);
|
||||
let extra = textureSample(t_extra, samp, uv);
|
||||
let aux = textureSample(t_aux, samp, uv);
|
||||
let dims = vec2<f32>(textureDimensions(t_height));
|
||||
let ts = 1.0 / dims;
|
||||
@@ -316,7 +367,7 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
// Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width.
|
||||
let k = g.mode.z * dims.x / 16.0;
|
||||
let n_height = normalize(vec3<f32>(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0));
|
||||
var n_detail = nrm_s * 2.0 - 1.0;
|
||||
var n_detail = snorm8(nrm_s);
|
||||
n_detail.y *= g.mode.w;
|
||||
let n_ts = rnm(n_height, normalize(n_detail));
|
||||
let n = normalize(t * n_ts.x + b * n_ts.y + n_geo * n_ts.z);
|
||||
@@ -325,24 +376,24 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
if (mode == 1) {
|
||||
let ch = i32(g.mode.y + 0.5);
|
||||
if (ch >= 11) {
|
||||
return lobe_view(ch, lobes, sheen_t, nrm_t.a, emis_t.a);
|
||||
return unlit(lobe_view(ch, lobes, sheen_t, nrm_t.a, emis_t.a, extra));
|
||||
}
|
||||
switch ch {
|
||||
case 0: { return data_out(base_s.rgb); }
|
||||
case 1: { return data_out(vec3<f32>(orm.b)); }
|
||||
case 2: { return data_out(vec3<f32>(orm.g)); }
|
||||
case 3: { return raw_out(n_ts * 0.5 + 0.5); }
|
||||
case 4: { return raw_out(vec3<f32>(hc * 0.5 + 0.5)); }
|
||||
case 5: { return data_out(emis); }
|
||||
case 6: { return raw_out(vec3<f32>(base_s.a)); }
|
||||
case 7: { return raw_out(vec3<f32>(orm.r)); }
|
||||
case 9: { return data_out(hgt.gba); }
|
||||
case 10: { return data_out(vec3<f32>(1.0 - orm.g)); }
|
||||
default: { return raw_out(vec3<f32>(orm.a)); }
|
||||
case 0: { return unlit(data_out(base_s.rgb)); }
|
||||
case 1: { return unlit(data_out(vec3<f32>(orm.b))); }
|
||||
case 2: { return unlit(data_out(vec3<f32>(orm.g))); }
|
||||
case 3: { return unlit(raw_out(n_ts * 0.5 + 0.5)); }
|
||||
case 4: { return unlit(raw_out(vec3<f32>(hc * 0.5 + 0.5))); }
|
||||
case 5: { return unlit(data_out(emis)); }
|
||||
case 6: { return unlit(raw_out(vec3<f32>(base_s.a))); }
|
||||
case 7: { return unlit(raw_out(vec3<f32>(orm.r))); }
|
||||
case 9: { return unlit(data_out(hgt.gba)); }
|
||||
case 10: { return unlit(data_out(vec3<f32>(1.0 - orm.g))); }
|
||||
default: { return unlit(raw_out(vec3<f32>(orm.a))); }
|
||||
}
|
||||
}
|
||||
if (mode == 2) {
|
||||
return raw_out(aux.rgb);
|
||||
return unlit(raw_out(aux.rgb));
|
||||
}
|
||||
if (mode == 3) {
|
||||
let c = floor(uv * 32.0);
|
||||
@@ -352,7 +403,7 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
let col = mix(vec3<f32>(0.85, 0.85, 0.85), vec3<f32>(0.18, 0.2, 0.24), chk) * (0.92 + 0.08 * f2);
|
||||
let tint = vec3<f32>(fract(uv.x), fract(uv.y), 0.5) * 0.25;
|
||||
let diff = max(dot(n, normalize(vec3<f32>(0.4, 0.8, 0.5))), 0.0) * 0.6 + 0.4;
|
||||
return data_out((col + tint) * diff);
|
||||
return unlit(data_out((col + tint) * diff));
|
||||
}
|
||||
|
||||
// Opacity: dithered alpha test (a new pattern per accumulated frame, so it averages out).
|
||||
@@ -373,6 +424,9 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
f0 = hgt.gba;
|
||||
diffuse_col = albedo * (1.0 - max(f0.r, max(f0.g, f0.b)));
|
||||
}
|
||||
// Transmission: that part of the dielectric base refracts instead of reflecting diffusely.
|
||||
let trans = extra.b * (1.0 - metal);
|
||||
diffuse_col *= 1.0 - trans;
|
||||
|
||||
// The extra lobes; their defaults (weights 0) leave the base shading as it is.
|
||||
let coat_w = lobes.r;
|
||||
@@ -392,8 +446,14 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
let ta1 = ta0 - n * dot(n, ta0);
|
||||
let ta = ta1 * inverseSqrt(max(dot(ta1, ta1), 1e-8));
|
||||
let ba = cross(n, ta);
|
||||
// The clear coat is smooth: it follows the mesh normal, not the normal and height channels.
|
||||
let nov_c = clamp(abs(dot(n_geo, v)), 1e-4, 1.0);
|
||||
// The clear coat follows the mesh normal (not the normal and height channels), turned by the
|
||||
// coat normal channel where it is painted (the flat default keeps the mesh normal exactly).
|
||||
var n_c = n_geo;
|
||||
let cn = coat_normal_ts(extra);
|
||||
if (coat_w > 0.0 && max(abs(cn.x), abs(cn.y)) > 0.004) {
|
||||
n_c = normalize(t * cn.x + b * cn.y + n_geo * cn.z);
|
||||
}
|
||||
let nov_c = clamp(abs(dot(n_c, v)), 1e-4, 1.0);
|
||||
let coat_t = 1.0 - coat_w * schlick(0.04, nov_c);
|
||||
// What reaches the layers below: the coat's transmission and the sheen albedo scaling.
|
||||
var base_scale = coat_t;
|
||||
@@ -420,11 +480,23 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
layers += pre_s * sheen_col * (sheen_e * ao * coat_t);
|
||||
}
|
||||
if (coat_w > 0.0) {
|
||||
let pre_c = textureSampleLevel(env_tex, env_samp, env_uv(reflect(-v, n_geo)), coat_rough * g.env.y).rgb;
|
||||
let pre_c = textureSampleLevel(env_tex, env_samp, env_uv(reflect(-v, n_c)), coat_rough * g.env.y).rgb;
|
||||
layers += pre_c * env_brdf(vec3<f32>(0.04), coat_rough, nov_c) * (coat_w * ao);
|
||||
}
|
||||
|
||||
if (trans > 0.0) {
|
||||
// shortcut: one refraction into the environment straight behind (no exit interface, no
|
||||
// scene behind the surface); the path tracer refracts through the whole mesh.
|
||||
var td = refract(-v, n, 1.0 / max(g.material.w, 1.0));
|
||||
if (dot(td, td) < 1e-6) {
|
||||
td = reflect(-v, n);
|
||||
}
|
||||
let behind = textureSampleLevel(env_tex, env_samp, env_uv(td), rough * g.env.y).rgb;
|
||||
layers += behind * albedo * (vec3<f32>(1.0) - env_brdf(f0, rough, nov)) * (trans * base_scale);
|
||||
}
|
||||
|
||||
var direct = vec3<f32>(0.0);
|
||||
var direct_diffuse = vec3<f32>(0.0);
|
||||
if (g.light.w > 0.0) {
|
||||
let l = normalize(g.light.xyz);
|
||||
let h = normalize(l + v);
|
||||
@@ -441,21 +513,24 @@ fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32
|
||||
let f = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - voh, 5.0);
|
||||
// Energy-conserving wrapped Lambert (plain Lambert where nothing scatters).
|
||||
let diff_nol = max((nol_raw + wrap) / ((1.0 + wrap) * (1.0 + wrap)), vec3<f32>(0.0));
|
||||
direct_diffuse = (vec3<f32>(1.0) - f) * diffuse_col / PI * diff_nol * (g.light.w * base_scale);
|
||||
direct = ((vec3<f32>(1.0) - f) * diffuse_col / PI * diff_nol + dv * f * nol) * (g.light.w * base_scale);
|
||||
if (sheen_max > 0.0) {
|
||||
let sa = sheen_rough * sheen_rough;
|
||||
direct += sheen_col * (d_charlie(sa, noh) * sheen_vis(nov, nol, sa) * nol * g.light.w * coat_t);
|
||||
}
|
||||
if (coat_w > 0.0) {
|
||||
let nol_c = max(dot(n_geo, l), 0.0);
|
||||
direct += vec3<f32>(ggx_dv(coat_rough * coat_rough, nov_c, nol_c, max(dot(n_geo, h), 0.0)) * schlick(0.04, voh) * coat_w * nol_c * g.light.w);
|
||||
let nol_c = max(dot(n_c, l), 0.0);
|
||||
direct += vec3<f32>(ggx_dv(coat_rough * coat_rough, nov_c, nol_c, max(dot(n_c, h), 0.0)) * schlick(0.04, voh) * coat_w * nol_c * g.light.w);
|
||||
}
|
||||
if (g.shadow.x > 0.5 && nol > 0.0) {
|
||||
direct *= shadow_factor(i.wpos, n_geo);
|
||||
let sh = shadow_factor(i.wpos, n_geo);
|
||||
direct *= sh;
|
||||
direct_diffuse *= sh;
|
||||
}
|
||||
}
|
||||
|
||||
return vec4<f32>((diffuse + spec) * base_scale + layers + direct + emis, 1.0);
|
||||
return Shaded(vec4<f32>((diffuse + spec) * base_scale + layers + direct + emis, 1.0), (diffuse * base_scale + direct_diffuse) * emis_t.a);
|
||||
}
|
||||
|
||||
// The 2D UV view: unlit material color (or the selected debug channel) over the UV layout.
|
||||
@@ -469,7 +544,7 @@ fn fs_uv(i: VOut) -> @location(0) vec4<f32> {
|
||||
if (ch >= 11) {
|
||||
let lobes = textureSample(t_lobes, samp, i.uv);
|
||||
let sheen = textureSample(t_sheen, samp, i.uv);
|
||||
return lobe_view(ch, lobes, sheen, textureSample(t_nrm, samp, i.uv).a, textureSample(t_emis, samp, i.uv).a);
|
||||
return lobe_view(ch, lobes, sheen, textureSample(t_nrm, samp, i.uv).a, textureSample(t_emis, samp, i.uv).a, textureSample(t_extra, samp, i.uv));
|
||||
}
|
||||
switch ch {
|
||||
case 1: { return data_out(vec3<f32>(orm.b)); }
|
||||
|
||||
@@ -5,10 +5,14 @@
|
||||
struct Post {
|
||||
a: vec4<f32>, // x exposure multiplier (2^EV), y tone mapping (0 linear, 1 ACES), z data view (1: no exposure, tone mapping or effects), w bloom strength
|
||||
b: vec4<f32>, // x vignette, y sharpen, z grain, w bloom threshold
|
||||
c: vec4<f32>, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample
|
||||
d: vec4<f32>, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1
|
||||
e: vec4<f32>, // x orthographic camera (1: pixels per world unit don't fall off with depth), yzw -
|
||||
};
|
||||
|
||||
@group(0) @binding(3) var<uniform> post: Post;
|
||||
@group(0) @binding(4) var bloom_tex: texture_2d<f32>;
|
||||
// The bloom pyramid in the post pass; the first extra input of the effect passes (fx.wgsl).
|
||||
@group(0) @binding(4) var fx_a: texture_2d<f32>;
|
||||
|
||||
// Narkowicz's fitted ACES filmic curve (pre-scaled so mid gray stays put).
|
||||
fn aces(x: vec3<f32>) -> vec3<f32> {
|
||||
@@ -61,7 +65,7 @@ fn fs_post(i: FsOut) -> @location(0) vec4<f32> {
|
||||
// Bloom adds light in scene space, so it is tone mapped with the pixel; over the backdrop
|
||||
// it glows on its own.
|
||||
let c = textureSampleLevel(src, src_samp, i.uv, 0.0);
|
||||
let glow = textureSampleLevel(bloom_tex, src_samp, i.uv, 0.0).rgb * post.a.w;
|
||||
let glow = textureSampleLevel(fx_a, src_samp, i.uv, 0.0).rgb * post.a.w;
|
||||
col = mix(backdrop(i.uv) + tonemap(glow), tonemap(c.rgb / max(c.a, 1e-4) + glow), clamp(c.a, 0.0, 1.0));
|
||||
} else {
|
||||
col = shade_px(i.uv);
|
||||
|
||||
@@ -0,0 +1,974 @@
|
||||
// GPU path tracing: one compute invocation per pixel adds `spp` samples to the accumulation
|
||||
// buffers. A line-by-line port of `trace.rs` (the CPU tracer is the oracle): the same random
|
||||
// streams, thin-lens camera, BVH traversal, material conventions, lobes, transmission,
|
||||
// next-event estimation with MIS, subsurface random walk, Russian roulette and firefly clamp.
|
||||
|
||||
const PI: f32 = 3.14159265358979;
|
||||
const TAU: f32 = 6.28318530717959;
|
||||
const NONE: u32 = 0xffffffffu;
|
||||
const BIG: f32 = 3.0e38;
|
||||
const WALK_STEPS: u32 = 48u;
|
||||
const STACK: u32 = 64u;
|
||||
const EDGE: f32 = 1e-5;
|
||||
const MAX_SETS: u32 = 256u;
|
||||
|
||||
struct Params {
|
||||
inv_vp: mat4x4<f32>,
|
||||
forward: vec4<f32>, // xyz camera forward, w ray offset (eps)
|
||||
size: vec4<u32>, // width, height, first sample index, samples this dispatch
|
||||
cfg: vec4<u32>, // bounces, specular/glossiness, environment light sampling, texture sets
|
||||
env: vec4<f32>, // sin and cos of the environment rotation
|
||||
sigma: vec4<f32>, // subsurface extinction per color channel
|
||||
eye: vec4<f32>, // camera position
|
||||
lens: vec4<f32>, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR
|
||||
// Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength.
|
||||
sets: array<vec4<f32>, MAX_SETS>,
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> P: Params;
|
||||
// Per node: (lo, first child or triangle), (hi, triangle count; 0 for inner nodes); floats as bits.
|
||||
@group(0) @binding(1) var<storage, read> nodes: array<vec4<u32>>;
|
||||
// Per triangle in BVH order: (p0, texture layer), (p1, tangent sign), (p2, 0), (vertex indices, 0);
|
||||
// floats as bits.
|
||||
@group(0) @binding(2) var<storage, read> tris: array<vec4<u32>>;
|
||||
// Per vertex: (normal, u), (tangent, v).
|
||||
@group(0) @binding(3) var<storage, read> verts: array<vec4<f32>>;
|
||||
// Environment importance sampling: row CDF (h), column CDFs (w·h), pixel probabilities (w·h).
|
||||
@group(0) @binding(4) var<storage, read> env_cdf: array<f32>;
|
||||
@group(0) @binding(5) var<storage, read_write> acc_hit: array<vec4<f32>>; // radiance, luminance²
|
||||
@group(0) @binding(6) var<storage, read_write> acc_alb: array<vec4<f32>>; // first-hit albedo, hits
|
||||
@group(0) @binding(7) var<storage, read_write> acc_nrm: array<vec4<f32>>; // shading normal, depth
|
||||
@group(0) @binding(8) var<storage, read_write> acc_env: array<vec4<f32>>; // environment of misses
|
||||
@group(0) @binding(9) var env_tex: texture_2d<f32>;
|
||||
// The renderer's display textures (compose::display packing), one layer per texture set.
|
||||
@group(0) @binding(10) var t_base: texture_2d_array<f32>;
|
||||
@group(0) @binding(11) var t_orm: texture_2d_array<f32>;
|
||||
@group(0) @binding(12) var t_normal: texture_2d_array<f32>;
|
||||
@group(0) @binding(13) var t_height: texture_2d_array<f32>;
|
||||
@group(0) @binding(14) var t_emissive: texture_2d_array<f32>;
|
||||
@group(0) @binding(15) var t_lobes: texture_2d_array<f32>;
|
||||
@group(0) @binding(16) var t_sheen: texture_2d_array<f32>;
|
||||
@group(0) @binding(17) var t_extra: texture_2d_array<f32>;
|
||||
|
||||
var<private> rng: u32;
|
||||
|
||||
fn pcg3d(a: vec3<u32>) -> vec3<u32> {
|
||||
var v = a * 1664525u + 1013904223u;
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
v = v ^ (v >> vec3<u32>(16u));
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
return v;
|
||||
}
|
||||
|
||||
// xorshift32, as `Rng::next`.
|
||||
fn rnd() -> f32 {
|
||||
rng ^= rng << 13u;
|
||||
rng ^= rng >> 17u;
|
||||
rng ^= rng << 5u;
|
||||
return f32(rng >> 8u) / 16777216.0;
|
||||
}
|
||||
|
||||
fn luminance(c: vec3<f32>) -> f32 {
|
||||
return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
|
||||
fn max3(c: vec3<f32>) -> f32 {
|
||||
return max(c.x, max(c.y, c.z));
|
||||
}
|
||||
|
||||
fn finite(x: f32) -> bool {
|
||||
return (bitcast<u32>(x) & 0x7f800000u) != 0x7f800000u;
|
||||
}
|
||||
|
||||
fn finite3(c: vec3<f32>) -> bool {
|
||||
return finite(c.x) && finite(c.y) && finite(c.z);
|
||||
}
|
||||
|
||||
fn normalize_or(v: vec3<f32>, fallback: vec3<f32>) -> vec3<f32> {
|
||||
let l2 = dot(v, v);
|
||||
if (l2 > 1e-30 && finite(l2)) {
|
||||
return v * inverseSqrt(l2);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// Duff et al. 2017 orthonormal basis (glam's `any_orthonormal_pair`).
|
||||
fn onb_t(n: vec3<f32>) -> vec3<f32> {
|
||||
let s = select(-1.0, 1.0, n.z >= 0.0);
|
||||
let a = -1.0 / (s + n.z);
|
||||
let b = n.x * n.y * a;
|
||||
return vec3<f32>(1.0 + s * n.x * n.x * a, s * b, -s * n.x);
|
||||
}
|
||||
|
||||
fn onb_b(n: vec3<f32>) -> vec3<f32> {
|
||||
let s = select(-1.0, 1.0, n.z >= 0.0);
|
||||
let a = -1.0 / (s + n.z);
|
||||
let b = n.x * n.y * a;
|
||||
return vec3<f32>(b, s + n.y * n.y * a, -n.y);
|
||||
}
|
||||
|
||||
// ---- Environment ----
|
||||
|
||||
fn dir_of(u: f32, v: f32) -> vec3<f32> {
|
||||
let theta = v * PI;
|
||||
let phi = u * TAU;
|
||||
return vec3<f32>(sin(theta) * cos(phi), cos(theta), sin(theta) * sin(phi));
|
||||
}
|
||||
|
||||
// atan2 for the elevation too: GPU acos is too coarse near the poles of a texel row.
|
||||
fn uv_of(d: vec3<f32>) -> vec2<f32> {
|
||||
let u = atan2(d.z, d.x) / TAU;
|
||||
return vec2<f32>(u - floor(u), atan2(length(d.xz), d.y) / PI);
|
||||
}
|
||||
|
||||
fn to_env(d: vec3<f32>) -> vec3<f32> {
|
||||
let s = P.env.x;
|
||||
let c = P.env.y;
|
||||
return vec3<f32>(c * d.x - s * d.z, d.y, s * d.x + c * d.z);
|
||||
}
|
||||
|
||||
fn env_texel(x: i32, y: i32) -> vec3<f32> {
|
||||
let dims = vec2<i32>(textureDimensions(env_tex));
|
||||
let xx = ((x % dims.x) + dims.x) % dims.x;
|
||||
let yy = clamp(y, 0, dims.y - 1);
|
||||
return textureLoad(env_tex, vec2<i32>(xx, yy), 0).rgb;
|
||||
}
|
||||
|
||||
// Bilinear lookup in environment space (`EnvImage::sample`).
|
||||
fn env_local(d: vec3<f32>) -> vec3<f32> {
|
||||
let dims = vec2<f32>(textureDimensions(env_tex));
|
||||
let uv = uv_of(d);
|
||||
let f = uv * dims - 0.5;
|
||||
let x0 = floor(f.x);
|
||||
let y0 = floor(f.y);
|
||||
let t = f - vec2<f32>(x0, y0);
|
||||
let xi = i32(x0);
|
||||
let yi = i32(y0);
|
||||
let a = mix(env_texel(xi, yi), env_texel(xi + 1, yi), t.x);
|
||||
let b = mix(env_texel(xi, yi + 1), env_texel(xi + 1, yi + 1), t.x);
|
||||
return mix(a, b, t.y);
|
||||
}
|
||||
|
||||
fn env(d: vec3<f32>) -> vec3<f32> {
|
||||
return env_local(to_env(d));
|
||||
}
|
||||
|
||||
fn env_pdf_local(d: vec3<f32>) -> f32 {
|
||||
let dims = textureDimensions(env_tex);
|
||||
let uv = uv_of(d);
|
||||
return texel_pdf(min(u32(uv.x * f32(dims.x)), dims.x - 1u), min(u32(uv.y * f32(dims.y)), dims.y - 1u));
|
||||
}
|
||||
|
||||
// Solid-angle density of sampling a direction in environment texel (x, y).
|
||||
fn texel_pdf(x: u32, y: u32) -> f32 {
|
||||
let dims = textureDimensions(env_tex);
|
||||
let w = dims.x;
|
||||
let h = dims.y;
|
||||
let s = sin(PI * (f32(y) + 0.5) / f32(h));
|
||||
let p = env_cdf[h + w * h + y * w + x];
|
||||
if (s <= 1e-6) {
|
||||
return 0.0;
|
||||
}
|
||||
return p * f32(w * h) / (2.0 * PI * PI * s);
|
||||
}
|
||||
|
||||
fn env_pdf(d: vec3<f32>) -> f32 {
|
||||
return env_pdf_local(to_env(d));
|
||||
}
|
||||
|
||||
// First index in env_cdf[start, start + n) whose value is >= goal (`partition_point`).
|
||||
fn lower_bound(start: u32, n: u32, goal: f32) -> u32 {
|
||||
var lo = 0u;
|
||||
var hi = n;
|
||||
loop {
|
||||
if (lo >= hi) {
|
||||
break;
|
||||
}
|
||||
let mid = (lo + hi) / 2u;
|
||||
if (env_cdf[start + mid] < goal) {
|
||||
lo = mid + 1u;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
// A world direction toward the environment chosen by brightness, and its density (0: none).
|
||||
fn sample_env() -> vec4<f32> {
|
||||
let u0 = rnd();
|
||||
let u1 = rnd();
|
||||
let u2 = rnd();
|
||||
let u3 = rnd();
|
||||
let dims = textureDimensions(env_tex);
|
||||
let w = dims.x;
|
||||
let h = dims.y;
|
||||
let y = min(lower_bound(0u, h, u0 * env_cdf[h - 1u]), h - 1u);
|
||||
let row = h + y * w;
|
||||
let x = min(lower_bound(row, w, u1 * env_cdf[row + w - 1u]), w - 1u);
|
||||
let e = dir_of((f32(x) + u2) / f32(w), (f32(y) + u3) / f32(h));
|
||||
// The texel's own density (round-tripping the direction through atan2 could land next door).
|
||||
let pdf = texel_pdf(x, y);
|
||||
let s = P.env.x;
|
||||
let c = P.env.y;
|
||||
return vec4<f32>(c * e.x + s * e.z, e.y, -s * e.x + c * e.z, pdf);
|
||||
}
|
||||
|
||||
// ---- Ray casts ----
|
||||
|
||||
struct Hit {
|
||||
t: f32,
|
||||
idx: u32,
|
||||
u: f32,
|
||||
v: f32,
|
||||
};
|
||||
|
||||
fn slab(n: u32, o: vec3<f32>, inv: vec3<f32>, tmax: f32) -> f32 {
|
||||
let lo = bitcast<vec3<f32>>(nodes[n * 2u].xyz);
|
||||
let hi = bitcast<vec3<f32>>(nodes[n * 2u + 1u].xyz);
|
||||
let t0 = (lo - o) * inv;
|
||||
let t1 = (hi - o) * inv;
|
||||
let tn = max(max3(min(t0, t1)), 0.0);
|
||||
let tf = min(min(min(max(t0.x, t1.x), max(t0.y, t1.y)), max(t0.z, t1.z)), tmax);
|
||||
return select(-1.0, tn, tn <= tf);
|
||||
}
|
||||
|
||||
// Vertex `k` of triangle `i` (BVH order).
|
||||
fn tri_p(i: u32, k: u32) -> vec3<f32> {
|
||||
return bitcast<vec3<f32>>(tris[i * 4u + k].xyz);
|
||||
}
|
||||
|
||||
// Möller–Trumbore, double sided, with the CPU's edge slack: (t, u, v), t < 0 for a miss.
|
||||
fn hit_tri(i: u32, o: vec3<f32>, d: vec3<f32>) -> vec3<f32> {
|
||||
let miss = vec3<f32>(-1.0);
|
||||
let p0 = tri_p(i, 0u);
|
||||
let e1 = tri_p(i, 1u) - p0;
|
||||
let e2 = tri_p(i, 2u) - p0;
|
||||
let p = cross(d, e2);
|
||||
let det = dot(e1, p);
|
||||
if (abs(det) < 1e-12) {
|
||||
return miss;
|
||||
}
|
||||
let inv = 1.0 / det;
|
||||
let s = o - p0;
|
||||
let u = dot(s, p) * inv;
|
||||
if (u < -EDGE || u > 1.0 + EDGE) {
|
||||
return miss;
|
||||
}
|
||||
let q = cross(s, e1);
|
||||
let v = dot(d, q) * inv;
|
||||
if (v < -EDGE || u + v > 1.0 + EDGE) {
|
||||
return miss;
|
||||
}
|
||||
let t = dot(e2, q) * inv;
|
||||
return select(miss, vec3<f32>(t, u, v), t > 0.0);
|
||||
}
|
||||
|
||||
// Closest hit before `tmax` (or any hit, for shadow rays); idx NONE when nothing is hit.
|
||||
fn traverse(o: vec3<f32>, d: vec3<f32>, tmax: f32, any_hit: bool) -> Hit {
|
||||
var best = Hit(tmax, NONE, 0.0, 0.0);
|
||||
// Zero direction components would give 0·∞ in the slab test.
|
||||
let sd = select(d, select(vec3<f32>(-1e-20), vec3<f32>(1e-20), d >= vec3<f32>(0.0)), abs(d) < vec3<f32>(1e-20));
|
||||
let inv = 1.0 / sd;
|
||||
var stack_n: array<u32, STACK>;
|
||||
var stack_t: array<f32, STACK>;
|
||||
let root = slab(0u, o, inv, best.t);
|
||||
if (root < 0.0) {
|
||||
return best;
|
||||
}
|
||||
stack_n[0] = 0u;
|
||||
stack_t[0] = root;
|
||||
var sp = 1u;
|
||||
loop {
|
||||
if (sp == 0u) {
|
||||
break;
|
||||
}
|
||||
sp -= 1u;
|
||||
let ni = stack_n[sp];
|
||||
if (stack_t[sp] > best.t) {
|
||||
continue;
|
||||
}
|
||||
let first = nodes[ni * 2u].w;
|
||||
let count = nodes[ni * 2u + 1u].w;
|
||||
if (count > 0u) {
|
||||
for (var i = first; i < first + count; i++) {
|
||||
let h = hit_tri(i, o, d);
|
||||
if (h.x > 0.0 && h.x < best.t) {
|
||||
best = Hit(h.x, i, h.y, h.z);
|
||||
if (any_hit) {
|
||||
return best;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Visit the nearer child first.
|
||||
let dl = slab(first, o, inv, best.t);
|
||||
let dr = slab(first + 1u, o, inv, best.t);
|
||||
if (dl >= 0.0 && dr >= 0.0 && sp + 2u <= STACK) {
|
||||
let near_first = dl <= dr;
|
||||
stack_n[sp] = select(first, first + 1u, near_first);
|
||||
stack_t[sp] = select(dl, dr, near_first);
|
||||
stack_n[sp + 1u] = select(first + 1u, first, near_first);
|
||||
stack_t[sp + 1u] = select(dr, dl, near_first);
|
||||
sp += 2u;
|
||||
} else if (dl >= 0.0 && sp < STACK) {
|
||||
stack_n[sp] = first;
|
||||
stack_t[sp] = dl;
|
||||
sp += 1u;
|
||||
} else if (dr >= 0.0 && sp < STACK) {
|
||||
stack_n[sp] = first + 1u;
|
||||
stack_t[sp] = dr;
|
||||
sp += 1u;
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
fn occluded(o: vec3<f32>, d: vec3<f32>) -> bool {
|
||||
return traverse(o, d, BIG, true).idx != NONE;
|
||||
}
|
||||
|
||||
// ---- Materials ----
|
||||
|
||||
// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy).
|
||||
fn texel(layer: u32, k: u32, uv: vec2<f32>, dx: i32, dy: i32) -> vec2<i32> {
|
||||
let info = P.sets[layer];
|
||||
let small = ((u32(info.z) >> k) & 1u) == 1u;
|
||||
let dims = select(max(vec2<i32>(info.xy), vec2<i32>(1)), vec2<i32>(1), small);
|
||||
let x = i32(floor(uv.x * f32(dims.x))) + dx;
|
||||
let y = i32(floor(uv.y * f32(dims.y))) + dy;
|
||||
return vec2<i32>(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y);
|
||||
}
|
||||
|
||||
struct Surface {
|
||||
pos: vec3<f32>,
|
||||
geo: vec3<f32>,
|
||||
n: vec3<f32>,
|
||||
tangent: vec3<f32>,
|
||||
diffuse: vec3<f32>,
|
||||
f0: vec3<f32>,
|
||||
roughness: f32,
|
||||
emissive: vec3<f32>,
|
||||
opacity: f32,
|
||||
anisotropy: f32,
|
||||
coat: f32,
|
||||
coat_roughness: f32,
|
||||
coat_n: vec3<f32>,
|
||||
sheen: vec3<f32>,
|
||||
sheen_roughness: f32,
|
||||
scatter: f32,
|
||||
// Transmissive part of the base, its tint, and whether the ray enters the mesh here.
|
||||
transmission: f32,
|
||||
base: vec3<f32>,
|
||||
front: bool,
|
||||
};
|
||||
|
||||
fn vertex_normal(i: u32, fallback: vec3<f32>) -> vec3<f32> {
|
||||
let n = verts[i * 2u].xyz;
|
||||
return select(n, fallback, dot(n, n) == 0.0);
|
||||
}
|
||||
|
||||
// Tangent-space normal blending (reoriented normal mapping).
|
||||
fn rnm(base: vec3<f32>, detail: vec3<f32>) -> vec3<f32> {
|
||||
let t = base + vec3<f32>(0.0, 0.0, 1.0);
|
||||
let u = detail * vec3<f32>(-1.0, -1.0, 1.0);
|
||||
return normalize_or(t * dot(t, u) - u * t.z, vec3<f32>(0.0, 0.0, 1.0));
|
||||
}
|
||||
|
||||
fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
|
||||
let p0 = tri_p(hit.idx, 0u);
|
||||
let p1 = tri_p(hit.idx, 1u);
|
||||
let p2 = tri_p(hit.idx, 2u);
|
||||
let ix = tris[hit.idx * 4u + 3u].xyz;
|
||||
let layer_in = tris[hit.idx * 4u].w;
|
||||
let layer = select(P.cfg.w, layer_in, layer_in < P.cfg.w);
|
||||
let tsign = select(1.0, -1.0, bitcast<f32>(tris[hit.idx * 4u + 1u].w) < 0.0);
|
||||
let u = hit.u;
|
||||
let v = hit.v;
|
||||
let w0 = 1.0 - u - v;
|
||||
var geo = normalize_or(cross(p1 - p0, p2 - p0), vec3<f32>(0.0, 1.0, 0.0));
|
||||
let nrm = vertex_normal(ix.x, geo) * w0 + vertex_normal(ix.y, geo) * u + vertex_normal(ix.z, geo) * v;
|
||||
var n_geo = normalize_or(nrm, geo);
|
||||
let front = dot(geo, d) <= 0.0;
|
||||
if (!front) {
|
||||
geo = -geo;
|
||||
}
|
||||
if (dot(n_geo, geo) < 0.0) {
|
||||
n_geo = -n_geo;
|
||||
}
|
||||
let a0 = verts[ix.x * 2u + 1u];
|
||||
let a1 = verts[ix.y * 2u + 1u];
|
||||
let a2 = verts[ix.z * 2u + 1u];
|
||||
let uv = vec2<f32>(verts[ix.x * 2u].w, a0.w) * w0 + vec2<f32>(verts[ix.y * 2u].w, a1.w) * u + vec2<f32>(verts[ix.z * 2u].w, a2.w) * v;
|
||||
let tw = a0.xyz * w0 + a1.xyz * u + a2.xyz * v;
|
||||
|
||||
let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0), layer, 0);
|
||||
let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0), layer, 0);
|
||||
let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0), layer, 0);
|
||||
let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0), layer, 0);
|
||||
let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0), layer, 0);
|
||||
let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0), layer, 0);
|
||||
let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0), layer, 0);
|
||||
let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0), layer, 0);
|
||||
|
||||
let info = P.sets[layer];
|
||||
let k = info.w * info.x / 16.0;
|
||||
var n_height = vec3<f32>(0.0, 0.0, 1.0);
|
||||
if (k != 0.0) {
|
||||
let hx = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r;
|
||||
let hy = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r;
|
||||
n_height = normalize_or(vec3<f32>(-hx * 0.5 * k, hy * 0.5 * k, 1.0), vec3<f32>(0.0, 0.0, 1.0));
|
||||
}
|
||||
// 8-bit normals centred on 128, so the flat normal (128, 128, 255) is exactly +z (with
|
||||
// `× 2 − 1` it would lean 0.3°, shifting every reflection).
|
||||
let detail = normalize_or((nrm_t.rgb * 255.0 - 128.0) / 127.0, vec3<f32>(0.0, 0.0, 1.0));
|
||||
let n_ts = rnm(n_height, detail);
|
||||
let tt = normalize_or(tw - n_geo * dot(n_geo, tw), onb_t(n_geo));
|
||||
let b = cross(n_geo, tt) * tsign;
|
||||
var n = normalize_or(tt * n_ts.x + b * n_ts.y + n_geo * n_ts.z, n_geo);
|
||||
if (dot(n, -d) <= 0.0) {
|
||||
n = n_geo;
|
||||
}
|
||||
let angle = clamp(lobes.a, 0.0, 1.0) * PI;
|
||||
let turned = tt * cos(angle) + b * sin(angle);
|
||||
let tangent = normalize_or(turned - n * dot(n, turned), onb_t(n));
|
||||
|
||||
let base = base_t.rgb;
|
||||
var diffuse: vec3<f32>;
|
||||
var f0: vec3<f32>;
|
||||
var metallic = 0.0;
|
||||
if (P.cfg.y != 0u) {
|
||||
f0 = clamp(hgt.gba, vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
diffuse = base * (1.0 - max3(f0));
|
||||
} else {
|
||||
metallic = clamp(orm.b, 0.0, 1.0);
|
||||
let level = clamp(orm.a, 0.0, 1.0);
|
||||
diffuse = base * (1.0 - metallic);
|
||||
f0 = mix(vec3<f32>(0.08 * level), base, metallic);
|
||||
}
|
||||
// The coat normal packs x and y as 128 + 127·n (flat: exactly 0); z is rebuilt.
|
||||
let coat_base = select(geo, n_geo, dot(n_geo, -d) > 0.0);
|
||||
let cxy = (extra.xy * 255.0 - 128.0) / 127.0;
|
||||
let c = normalize_or(vec3<f32>(cxy, sqrt(max(1.0 - dot(cxy, cxy), 0.0))), vec3<f32>(0.0, 0.0, 1.0));
|
||||
let coat_turned = normalize_or(tt * c.x + b * c.y + coat_base * c.z, coat_base);
|
||||
var s: Surface;
|
||||
s.pos = o + d * hit.t;
|
||||
s.geo = geo;
|
||||
s.n = n;
|
||||
s.tangent = tangent;
|
||||
s.diffuse = diffuse;
|
||||
s.f0 = f0;
|
||||
s.roughness = clamp(orm.g, 0.045, 1.0);
|
||||
s.emissive = emi.rgb;
|
||||
s.opacity = clamp(base_t.a, 0.0, 1.0);
|
||||
s.anisotropy = clamp(lobes.b, 0.0, 1.0);
|
||||
s.coat = clamp(lobes.r, 0.0, 1.0);
|
||||
s.coat_roughness = max(clamp(lobes.g, 0.0, 1.0), 0.045);
|
||||
s.coat_n = select(coat_base, coat_turned, dot(coat_turned, -d) > 0.0);
|
||||
s.sheen = clamp(sheen_t.rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * clamp(sheen_t.a, 0.0, 1.0);
|
||||
s.sheen_roughness = max(clamp(nrm_t.a, 0.0, 1.0), 0.07);
|
||||
s.scatter = clamp(emi.a, 0.0, 1.0);
|
||||
s.transmission = clamp(extra.b, 0.0, 1.0) * (1.0 - metallic);
|
||||
s.base = clamp(base, vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
s.front = front;
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---- BSDF ----
|
||||
|
||||
fn schlick(f0: vec3<f32>, cos_t: f32) -> vec3<f32> {
|
||||
return f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - clamp(cos_t, 0.0, 1.0), 5.0);
|
||||
}
|
||||
|
||||
fn coat_fresnel(cos_t: f32) -> f32 {
|
||||
return schlick(vec3<f32>(0.04), cos_t).x;
|
||||
}
|
||||
|
||||
fn cosine_local(u1: f32, u2: f32) -> vec3<f32> {
|
||||
let r = sqrt(u1);
|
||||
let phi = TAU * u2;
|
||||
return vec3<f32>(r * cos(phi), r * sin(phi), sqrt(max(1.0 - u1, 0.0)));
|
||||
}
|
||||
|
||||
fn cosine_around(n: vec3<f32>) -> vec3<f32> {
|
||||
let u1 = rnd();
|
||||
let u2 = rnd();
|
||||
let l = cosine_local(u1, u2);
|
||||
return onb_t(n) * l.x + onb_b(n) * l.y + n * l.z;
|
||||
}
|
||||
|
||||
fn smith_g1(w: vec3<f32>, at: f32, ab: f32) -> f32 {
|
||||
let z = max(w.z, 1e-6);
|
||||
return 2.0 * z / (z + sqrt(at * at * w.x * w.x + ab * ab * w.y * w.y + z * z));
|
||||
}
|
||||
|
||||
fn sample_vndf(ve: vec3<f32>, at: f32, ab: f32, u1: f32, u2: f32) -> vec3<f32> {
|
||||
let vh = normalize_or(vec3<f32>(at * ve.x, ab * ve.y, ve.z), vec3<f32>(0.0, 0.0, 1.0));
|
||||
let len2 = vh.x * vh.x + vh.y * vh.y;
|
||||
let t1 = select(vec3<f32>(1.0, 0.0, 0.0), vec3<f32>(-vh.y, vh.x, 0.0) / sqrt(len2), len2 > 0.0);
|
||||
let t2 = cross(vh, t1);
|
||||
let r = sqrt(u1);
|
||||
let phi = TAU * u2;
|
||||
let p1 = r * cos(phi);
|
||||
let s = 0.5 * (1.0 + vh.z);
|
||||
let p2 = (1.0 - s) * sqrt(max(1.0 - p1 * p1, 0.0)) + s * r * sin(phi);
|
||||
let nh = t1 * p1 + t2 * p2 + vh * sqrt(max(1.0 - p1 * p1 - p2 * p2, 0.0));
|
||||
return normalize_or(vec3<f32>(at * nh.x, ab * nh.y, max(nh.z, 1e-6)), vec3<f32>(0.0, 0.0, 1.0));
|
||||
}
|
||||
|
||||
struct Ggx {
|
||||
t: vec3<f32>,
|
||||
b: vec3<f32>,
|
||||
n: vec3<f32>,
|
||||
v: vec3<f32>,
|
||||
at: f32,
|
||||
ab: f32,
|
||||
};
|
||||
|
||||
fn ggx_new(t: vec3<f32>, n: vec3<f32>, v: vec3<f32>, at: f32, ab: f32) -> Ggx {
|
||||
let b = cross(n, t);
|
||||
return Ggx(t, b, n, vec3<f32>(dot(v, t), dot(v, b), max(dot(v, n), 1e-4)), max(at, 1e-3), max(ab, 1e-3));
|
||||
}
|
||||
|
||||
fn ggx_local(g: Ggx, w: vec3<f32>) -> vec3<f32> {
|
||||
return vec3<f32>(dot(w, g.t), dot(w, g.b), dot(w, g.n));
|
||||
}
|
||||
|
||||
fn ggx_d(g: Ggx, h: vec3<f32>) -> f32 {
|
||||
let k = (h.x / g.at) * (h.x / g.at) + (h.y / g.ab) * (h.y / g.ab) + h.z * h.z;
|
||||
return 1.0 / max(PI * g.at * g.ab * k * k, 1e-12);
|
||||
}
|
||||
|
||||
// (D·G / (4 cos θv), density of `ggx_sample`, cos(l, h), 1) toward `w`; w = 0 when below.
|
||||
fn ggx_eval(g: Ggx, w: vec3<f32>) -> vec4<f32> {
|
||||
let l = ggx_local(g, w);
|
||||
if (l.z <= 0.0) {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
let h = normalize_or(l + g.v, vec3<f32>(0.0, 0.0, 1.0));
|
||||
let pdf = smith_g1(g.v, g.at, g.ab) * ggx_d(g, h) / (4.0 * g.v.z);
|
||||
return vec4<f32>(pdf * smith_g1(l, g.at, g.ab), pdf, dot(l, h), 1.0);
|
||||
}
|
||||
|
||||
// A world direction reflected off a visible normal; w = 0 when it points below.
|
||||
fn ggx_sample(g: Ggx, u1: f32, u2: f32) -> vec4<f32> {
|
||||
let h = sample_vndf(g.v, g.at, g.ab, u1, u2);
|
||||
let l = h * 2.0 * dot(g.v, h) - g.v;
|
||||
if (l.z <= 0.0) {
|
||||
return vec4<f32>(0.0);
|
||||
}
|
||||
return vec4<f32>(g.t * l.x + g.b * l.y + g.n * l.z, 1.0);
|
||||
}
|
||||
|
||||
fn d_charlie(a: f32, noh: f32) -> f32 {
|
||||
let inv = 1.0 / a;
|
||||
return (2.0 + inv) * pow(max(1.0 - noh * noh, 1e-4), inv * 0.5) / TAU;
|
||||
}
|
||||
|
||||
fn sheen_l(x: f32, o: f32) -> f32 {
|
||||
let a = mix(21.5473, 25.3245, o);
|
||||
let b = mix(3.82987, 3.32435, o);
|
||||
let c = mix(0.19823, 0.16801, o);
|
||||
let d = mix(-1.97760, -1.27393, o);
|
||||
let e = mix(-4.32054, -4.85967, o);
|
||||
return a / (1.0 + b * pow(max(x, 1e-4), c)) + d * x + e;
|
||||
}
|
||||
|
||||
fn sheen_lambda(cos_t: f32, a: f32) -> f32 {
|
||||
let o = (1.0 - a) * (1.0 - a);
|
||||
if (cos_t < 0.5) {
|
||||
return exp(sheen_l(cos_t, o));
|
||||
}
|
||||
return exp(2.0 * sheen_l(0.5, o) - sheen_l(1.0 - cos_t, o));
|
||||
}
|
||||
|
||||
fn sheen_vis(nov: f32, nol: f32, a: f32) -> f32 {
|
||||
return clamp(1.0 / ((1.0 + sheen_lambda(nov, a) + sheen_lambda(nol, a)) * 4.0 * nov * max(nol, 1e-4)), 0.0, 1.0);
|
||||
}
|
||||
|
||||
fn sheen_albedo(nov: f32, r: f32) -> f32 {
|
||||
let a = 1.2416 - 1.7580 * r + 1.7164 * r * r;
|
||||
let b = 6.2757 / (r + 0.2077) - 8.6381 + 4.4979 * r;
|
||||
let q = 1.2287 - 0.5161 * r;
|
||||
let c = 0.1121 * r - 0.3840 * r * r;
|
||||
return clamp(a * exp(-b * pow(max(nov, 0.0), q)) + c, 0.0, 1.0);
|
||||
}
|
||||
|
||||
struct Bsdf {
|
||||
spec: Ggx,
|
||||
coat: Ggx,
|
||||
f0: vec3<f32>,
|
||||
diffuse: vec3<f32>,
|
||||
fv: vec3<f32>,
|
||||
coat_weight: f32,
|
||||
coat_t: f32,
|
||||
sheen: vec3<f32>,
|
||||
sheen_a: f32,
|
||||
sheen_r: f32,
|
||||
sheen_ev: f32,
|
||||
p: vec4<f32>,
|
||||
walk_albedo: vec3<f32>,
|
||||
p_walk: f32,
|
||||
};
|
||||
|
||||
fn bsdf_new(s: Surface, v: vec3<f32>) -> Bsdf {
|
||||
let a = max(s.roughness * s.roughness, 1e-3);
|
||||
let spec = ggx_new(s.tangent, s.n, v, a * (1.0 + s.anisotropy), a * (1.0 - s.anisotropy));
|
||||
let coat_a = s.coat_roughness * s.coat_roughness;
|
||||
let coat = ggx_new(onb_t(s.coat_n), s.coat_n, v, coat_a, coat_a);
|
||||
let fv = schlick(s.f0, spec.v.z);
|
||||
let coat_t = 1.0 - s.coat * coat_fresnel(coat.v.z);
|
||||
let sheen_ev = sheen_albedo(spec.v.z, s.sheen_roughness);
|
||||
let base = coat_t * (1.0 - max3(s.sheen) * sheen_ev);
|
||||
let diffuse = s.diffuse * (1.0 - s.scatter);
|
||||
let walk_albedo = s.diffuse * s.scatter * (vec3<f32>(1.0) - fv) * base;
|
||||
var w = vec4<f32>(luminance(fv) * base, luminance(diffuse * (vec3<f32>(1.0) - fv)) * base, luminance(s.sheen) * sheen_ev * coat_t, s.coat * coat_fresnel(coat.v.z));
|
||||
let sum = w.x + w.y + w.z + w.w;
|
||||
w = select(vec4<f32>(0.0), max(w, vec4<f32>(0.1 * sum)), w > vec4<f32>(1e-5));
|
||||
let total = w.x + w.y + w.z + w.w;
|
||||
let p = select(vec4<f32>(1.0, 0.0, 0.0, 0.0), w / total, total > 0.0);
|
||||
let walk = luminance(walk_albedo);
|
||||
let p_walk = select(0.0, clamp(walk / (walk + sum), 0.05, 0.95), walk > 1e-5);
|
||||
return Bsdf(spec, coat, s.f0, diffuse, fv, s.coat, coat_t, s.sheen, s.sheen_roughness * s.sheen_roughness, s.sheen_roughness, sheen_ev, p, walk_albedo, p_walk);
|
||||
}
|
||||
|
||||
// BRDF × cos toward `w` (xyz) and the density of `bsdf_sample` picking it (w).
|
||||
fn bsdf_eval(b: Bsdf, w: vec3<f32>) -> vec4<f32> {
|
||||
var f = vec3<f32>(0.0);
|
||||
var pdf = 0.0;
|
||||
let l = ggx_local(b.spec, w);
|
||||
if (l.z > 0.0) {
|
||||
let m = max3(b.sheen);
|
||||
var base = b.coat_t;
|
||||
if (m > 0.0) {
|
||||
base *= min(1.0 - m * b.sheen_ev, 1.0 - m * sheen_albedo(l.z, b.sheen_r));
|
||||
}
|
||||
let e = ggx_eval(b.spec, w);
|
||||
if (e.w > 0.0) {
|
||||
f += schlick(b.f0, e.z) * e.x * base;
|
||||
pdf += b.p.x * e.y;
|
||||
}
|
||||
f += b.diffuse * (vec3<f32>(1.0) - b.fv) * (l.z / PI * base);
|
||||
pdf += (b.p.y + b.p.z) * l.z / PI;
|
||||
if (m > 0.0) {
|
||||
let h = normalize_or(l + b.spec.v, vec3<f32>(0.0, 0.0, 1.0));
|
||||
f += b.sheen * (d_charlie(b.sheen_a, h.z) * sheen_vis(b.spec.v.z, l.z, b.sheen_a) * l.z * b.coat_t);
|
||||
}
|
||||
}
|
||||
if (b.coat_weight > 0.0) {
|
||||
let e = ggx_eval(b.coat, w);
|
||||
if (e.w > 0.0) {
|
||||
f += vec3<f32>(b.coat_weight * coat_fresnel(e.z) * e.x);
|
||||
pdf += b.p.w * e.y;
|
||||
}
|
||||
}
|
||||
return vec4<f32>(f, pdf);
|
||||
}
|
||||
|
||||
fn bsdf_sample(b: Bsdf) -> vec4<f32> {
|
||||
let u0 = rnd();
|
||||
let u1 = rnd();
|
||||
let u2 = rnd();
|
||||
if (u0 < b.p.x) {
|
||||
return ggx_sample(b.spec, u1, u2);
|
||||
}
|
||||
if (u0 < b.p.x + b.p.y + b.p.z) {
|
||||
let l = cosine_local(u1, u2);
|
||||
return vec4<f32>(b.spec.t * l.x + b.spec.b * l.y + b.spec.n * l.z, 1.0);
|
||||
}
|
||||
return ggx_sample(b.coat, u1, u2);
|
||||
}
|
||||
|
||||
// ---- Transmission ----
|
||||
|
||||
// Unpolarized Fresnel reflectance of a dielectric interface; eta = n(incident) / n(other side).
|
||||
fn fresnel_dielectric(cos_i: f32, eta: f32) -> f32 {
|
||||
let sin2_t = eta * eta * max(1.0 - cos_i * cos_i, 0.0);
|
||||
if (sin2_t >= 1.0) {
|
||||
return 1.0;
|
||||
}
|
||||
let cos_t = sqrt(1.0 - sin2_t);
|
||||
let rs = (eta * cos_i - cos_t) / (eta * cos_i + cos_t);
|
||||
let rp = (cos_i - eta * cos_t) / (cos_i + eta * cos_t);
|
||||
return 0.5 * (rs * rs + rp * rp);
|
||||
}
|
||||
|
||||
// Density standing in for a lobe next-event estimation never samples.
|
||||
const UNSAMPLED_PDF: f32 = 1e15;
|
||||
|
||||
struct Glass {
|
||||
dir: vec3<f32>,
|
||||
w: vec3<f32>,
|
||||
ok: bool,
|
||||
};
|
||||
|
||||
// The transmissive base as a rough dielectric interface: reflect with the Fresnel at the IOR,
|
||||
// else refract into (or out of) the mesh, tinted by the base color on the way in.
|
||||
fn dielectric(s: Surface, v: vec3<f32>) -> Glass {
|
||||
let a = max(s.roughness * s.roughness, 1e-3);
|
||||
let lobe = ggx_new(s.tangent, s.n, v, a, a);
|
||||
let u1 = rnd();
|
||||
let u2 = rnd();
|
||||
let hl = sample_vndf(lobe.v, a, a, u1, u2);
|
||||
let h = lobe.t * hl.x + lobe.b * hl.y + lobe.n * hl.z;
|
||||
let cos_i = max(dot(v, h), 1e-6);
|
||||
let ior = max(P.lens.z, 1.0);
|
||||
let eta = select(ior, 1.0 / ior, s.front);
|
||||
if (rnd() < fresnel_dielectric(cos_i, eta)) {
|
||||
let l = h * 2.0 * cos_i - v;
|
||||
let ll = ggx_local(lobe, l);
|
||||
return Glass(l, vec3<f32>(smith_g1(ll, a, a)), dot(l, s.geo) > 0.0 && ll.z > 0.0);
|
||||
}
|
||||
let cos_t = sqrt(max(1.0 - eta * eta * (1.0 - cos_i * cos_i), 0.0));
|
||||
let l = normalize_or(h * (eta * cos_i - cos_t) - v * eta, -v);
|
||||
let ll = ggx_local(lobe, l);
|
||||
let tint = select(vec3<f32>(1.0), s.base, s.front);
|
||||
return Glass(l, tint * smith_g1(-ll, a, a), dot(l, s.geo) < 0.0 && ll.z < 0.0);
|
||||
}
|
||||
|
||||
// ---- Transport ----
|
||||
|
||||
struct Walk {
|
||||
exit: vec3<f32>,
|
||||
out: vec3<f32>,
|
||||
w: vec3<f32>,
|
||||
ok: bool,
|
||||
};
|
||||
|
||||
fn random_walk(s: Surface) -> Walk {
|
||||
let sigma = P.sigma.xyz;
|
||||
var p = s.pos - s.geo * P.forward.w;
|
||||
var d = cosine_around(-s.geo);
|
||||
var w = vec3<f32>(1.0);
|
||||
for (var i = 0u; i < WALK_STEPS; i++) {
|
||||
let c = min(u32(rnd() * 3.0), 2u);
|
||||
let t = -log(max(1.0 - rnd(), 1e-12)) / sigma[c];
|
||||
let hit = traverse(p, d, t, false);
|
||||
if (hit.idx != NONE) {
|
||||
let tr = exp(-sigma * hit.t);
|
||||
w *= tr / max((tr.x + tr.y + tr.z) / 3.0, 1e-30);
|
||||
let q0 = tri_p(hit.idx, 0u);
|
||||
let n = normalize_or(cross(tri_p(hit.idx, 1u) - q0, tri_p(hit.idx, 2u) - q0), -d);
|
||||
let out = select(-n, n, dot(n, d) > 0.0);
|
||||
return Walk(p + d * hit.t, out, w, finite3(w));
|
||||
}
|
||||
let tr = exp(-sigma * t);
|
||||
w *= sigma * tr / max(dot(sigma * tr, vec3<f32>(1.0 / 3.0)), 1e-30);
|
||||
p += d * t;
|
||||
let z = 1.0 - 2.0 * rnd();
|
||||
let phi = TAU * rnd();
|
||||
let r = sqrt(max(1.0 - z * z, 0.0));
|
||||
d = vec3<f32>(r * cos(phi), r * sin(phi), z);
|
||||
}
|
||||
return Walk(vec3<f32>(0.0), vec3<f32>(0.0), vec3<f32>(0.0), false);
|
||||
}
|
||||
|
||||
fn mis(a: f32, b: f32) -> f32 {
|
||||
let a2 = a * a;
|
||||
let b2 = b * b;
|
||||
return select(0.0, a2 / (a2 + b2), a2 + b2 > 0.0);
|
||||
}
|
||||
|
||||
fn clamp_firefly(c: vec3<f32>) -> vec3<f32> {
|
||||
let lum = luminance(c);
|
||||
return select(c, c * (32.0 / lum), lum > 32.0);
|
||||
}
|
||||
|
||||
// Next-event estimation toward the environment from `pos` (geometric normal `geo`), through
|
||||
// the BSDF `b` (its sampling density scaled by `keep`) or, with `lambert`, a Lambertian exit.
|
||||
fn next_event(pos: vec3<f32>, geo: vec3<f32>, thr: vec3<f32>, b: Bsdf, keep: f32, lambert: bool) -> vec3<f32> {
|
||||
if (P.cfg.z == 0u) {
|
||||
return vec3<f32>(0.0);
|
||||
}
|
||||
let e = sample_env();
|
||||
let wl = e.xyz;
|
||||
let pdf_env = e.w;
|
||||
if (pdf_env <= 0.0 || dot(wl, geo) <= 0.0) {
|
||||
return vec3<f32>(0.0);
|
||||
}
|
||||
var f: vec3<f32>;
|
||||
var pdf_brdf: f32;
|
||||
if (lambert) {
|
||||
let c = max(dot(wl, geo), 0.0) / PI;
|
||||
f = vec3<f32>(c);
|
||||
pdf_brdf = c;
|
||||
} else {
|
||||
let r = bsdf_eval(b, wl);
|
||||
f = r.xyz;
|
||||
pdf_brdf = r.w * keep;
|
||||
}
|
||||
if (max3(f) <= 0.0 || occluded(pos + geo * P.forward.w, wl)) {
|
||||
return vec3<f32>(0.0);
|
||||
}
|
||||
return clamp_firefly(thr * f * env(wl) * (mis(pdf_env, pdf_brdf) / pdf_env));
|
||||
}
|
||||
|
||||
struct Sample {
|
||||
radiance: vec3<f32>,
|
||||
albedo: vec3<f32>,
|
||||
normal: vec3<f32>,
|
||||
depth: f32,
|
||||
hit: bool,
|
||||
};
|
||||
|
||||
fn trace(o_in: vec3<f32>, d_in: vec3<f32>) -> Sample {
|
||||
let eps = P.forward.w;
|
||||
var o = o_in;
|
||||
var d = d_in;
|
||||
var out = Sample(vec3<f32>(0.0), vec3<f32>(0.0), vec3<f32>(0.0), 0.0, false);
|
||||
var thr = vec3<f32>(1.0);
|
||||
var l = vec3<f32>(0.0);
|
||||
var bounce = 0u;
|
||||
var brdf_pdf = -1.0;
|
||||
let bounces = P.cfg.x;
|
||||
for (var it = 0u; it < bounces + 24u; it++) {
|
||||
let hit = traverse(o, d, BIG, false);
|
||||
if (hit.idx == NONE) {
|
||||
if (brdf_pdf < 0.0) {
|
||||
return Sample(vec3<f32>(0.0), vec3<f32>(0.0), vec3<f32>(0.0), 0.0, false);
|
||||
}
|
||||
var w = 1.0;
|
||||
if (P.cfg.z != 0u) {
|
||||
w = mis(brdf_pdf, env_pdf(d));
|
||||
}
|
||||
l += clamp_firefly(thr * env(d) * w);
|
||||
break;
|
||||
}
|
||||
let s = surface(hit, o, d);
|
||||
if (rnd() > s.opacity) {
|
||||
o = s.pos - s.geo * eps;
|
||||
continue;
|
||||
}
|
||||
if (!out.hit) {
|
||||
out.hit = true;
|
||||
out.albedo = min(s.diffuse + s.f0, vec3<f32>(1.0));
|
||||
out.normal = s.n;
|
||||
out.depth = length(s.pos - o_in);
|
||||
}
|
||||
l += thr * s.emissive;
|
||||
if (bounce >= bounces) {
|
||||
break;
|
||||
}
|
||||
// Transmission is picked by its weight (a glass event, without next-event estimation).
|
||||
let glass = s.transmission > 0.0 && rnd() < s.transmission;
|
||||
let b = bsdf_new(s, -d);
|
||||
let keep = 1.0 - b.p_walk;
|
||||
if (!glass) {
|
||||
l += next_event(s.pos, s.geo, thr, b, keep, false);
|
||||
}
|
||||
var wi: vec3<f32>;
|
||||
var geo: vec3<f32>;
|
||||
if (glass) {
|
||||
let g = dielectric(s, -d);
|
||||
if (!g.ok) {
|
||||
break;
|
||||
}
|
||||
thr *= g.w;
|
||||
brdf_pdf = UNSAMPLED_PDF;
|
||||
o = s.pos;
|
||||
wi = g.dir;
|
||||
geo = s.geo;
|
||||
} else if (b.p_walk > 0.0 && rnd() < b.p_walk) {
|
||||
let walk = random_walk(s);
|
||||
if (!walk.ok) {
|
||||
break;
|
||||
}
|
||||
thr *= b.walk_albedo * walk.w / b.p_walk;
|
||||
l += next_event(walk.exit, walk.out, thr, b, keep, true);
|
||||
wi = cosine_around(walk.out);
|
||||
brdf_pdf = max(dot(wi, walk.out), 1e-6) / PI;
|
||||
o = walk.exit;
|
||||
geo = walk.out;
|
||||
} else {
|
||||
let smp = bsdf_sample(b);
|
||||
if (smp.w == 0.0) {
|
||||
break;
|
||||
}
|
||||
wi = smp.xyz;
|
||||
let e = bsdf_eval(b, wi);
|
||||
if (e.w <= 0.0) {
|
||||
break;
|
||||
}
|
||||
thr *= e.xyz / (e.w * keep);
|
||||
brdf_pdf = e.w * keep;
|
||||
o = s.pos;
|
||||
geo = s.geo;
|
||||
}
|
||||
if (bounce >= 2u) {
|
||||
let p = clamp(max3(thr), 0.05, 0.95);
|
||||
if (rnd() > p) {
|
||||
break;
|
||||
}
|
||||
thr /= p;
|
||||
}
|
||||
o += geo * eps * select(-1.0, 1.0, dot(wi, geo) >= 0.0);
|
||||
d = wi;
|
||||
bounce += 1u;
|
||||
}
|
||||
if (!out.hit) {
|
||||
return out;
|
||||
}
|
||||
out.radiance = select(vec3<f32>(0.0), l, finite3(l));
|
||||
return out;
|
||||
}
|
||||
|
||||
// The camera ray between the near and far points of a pixel, through a random point of the thin
|
||||
// lens when the scene has one (`TraceScene::camera_ray`): (origin, direction).
|
||||
fn camera_ray(near: vec3<f32>, far: vec3<f32>) -> array<vec3<f32>, 2> {
|
||||
let dir = normalize_or(far - near, P.forward.xyz);
|
||||
let fwd = P.forward.xyz;
|
||||
let along = dot(dir, fwd);
|
||||
if (P.lens.y <= 0.0 || along <= 1e-6) {
|
||||
return array<vec3<f32>, 2>(near, dir);
|
||||
}
|
||||
let focal = near + dir * ((P.lens.x - dot(near - P.eye.xyz, fwd)) / along);
|
||||
let right = normalize_or(cross(fwd, vec3<f32>(0.0, 1.0, 0.0)), vec3<f32>(1.0, 0.0, 0.0));
|
||||
let up = cross(right, fwd);
|
||||
let r = P.lens.y * sqrt(rnd());
|
||||
let phi = TAU * rnd();
|
||||
let origin = near + (right * cos(phi) + up * sin(phi)) * r;
|
||||
return array<vec3<f32>, 2>(origin, normalize_or(focal - origin, dir));
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn trace_main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let w = P.size.x;
|
||||
let h = P.size.y;
|
||||
if (id.x >= w || id.y >= h) {
|
||||
return;
|
||||
}
|
||||
let i = id.y * w + id.x;
|
||||
var hit = acc_hit[i];
|
||||
var alb = acc_alb[i];
|
||||
var nrm = acc_nrm[i];
|
||||
var bg = acc_env[i];
|
||||
for (var k = 0u; k < P.size.w; k++) {
|
||||
let pass_index = P.size.z + k;
|
||||
rng = pcg3d(vec3<u32>(id.x, id.y, pass_index * 7919u + 17u)).x | 1u;
|
||||
let jx = rnd();
|
||||
let jy = rnd();
|
||||
let ndc = vec2<f32>((f32(id.x) + jx) / f32(w) * 2.0 - 1.0, 1.0 - (f32(id.y) + jy) / f32(h) * 2.0);
|
||||
let a = P.inv_vp * vec4<f32>(ndc, 0.0, 1.0);
|
||||
let b = P.inv_vp * vec4<f32>(ndc, 1.0, 1.0);
|
||||
let ray = camera_ray(a.xyz / a.w, b.xyz / b.w);
|
||||
let origin = ray[0];
|
||||
let dir = ray[1];
|
||||
let s = trace(origin, dir);
|
||||
if (s.hit) {
|
||||
hit += vec4<f32>(s.radiance, luminance(s.radiance) * luminance(s.radiance));
|
||||
alb += vec4<f32>(s.albedo, 1.0);
|
||||
nrm += vec4<f32>(s.normal, s.depth);
|
||||
} else {
|
||||
bg += vec4<f32>(env(dir), 0.0);
|
||||
}
|
||||
}
|
||||
acc_hit[i] = hit;
|
||||
acc_alb[i] = alb;
|
||||
acc_nrm[i] = nrm;
|
||||
acc_env[i] = bg;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// GPU path tracing, after the samples: the edge-avoiding à-trous denoiser on demodulated radiance
|
||||
// and the display resolve (tone mapping over the studio backdrop or the environment), ports of
|
||||
// `Tracer::denoise` and `Tracer::rgba8`.
|
||||
|
||||
struct Post {
|
||||
size: vec4<u32>, // width, height, samples, à-trous step
|
||||
display: vec4<f32>, // exposure multiplier, ACES (1) or linear (0), environment opacity, denoise (1)
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> Q: Post;
|
||||
@group(0) @binding(1) var<storage, read> acc_hit: array<vec4<f32>>;
|
||||
@group(0) @binding(2) var<storage, read> acc_alb: array<vec4<f32>>;
|
||||
@group(0) @binding(3) var<storage, read> acc_nrm: array<vec4<f32>>;
|
||||
@group(0) @binding(4) var<storage, read> acc_env: array<vec4<f32>>;
|
||||
// Demodulated radiance and its variance: read from `src`, written to `dst`.
|
||||
@group(0) @binding(5) var<storage, read> src: array<vec4<f32>>;
|
||||
@group(0) @binding(6) var<storage, read_write> dst: array<vec4<f32>>;
|
||||
@group(0) @binding(7) var out: texture_storage_2d<rgba8unorm, write>;
|
||||
|
||||
fn luminance(c: vec3<f32>) -> f32 {
|
||||
return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
|
||||
fn normalize_or(v: vec3<f32>, fallback: vec3<f32>) -> vec3<f32> {
|
||||
let l2 = dot(v, v);
|
||||
return select(fallback, v * inverseSqrt(l2), l2 > 1e-30);
|
||||
}
|
||||
|
||||
struct Guide {
|
||||
albedo: vec3<f32>,
|
||||
normal: vec3<f32>,
|
||||
depth: f32,
|
||||
hit: bool,
|
||||
};
|
||||
|
||||
fn guide(i: u32) -> Guide {
|
||||
let a = acc_alb[i];
|
||||
let n = max(a.w, 1.0);
|
||||
let nd = acc_nrm[i];
|
||||
return Guide(max(a.rgb / n, vec3<f32>(0.02)), normalize_or(nd.xyz, vec3<f32>(0.0, 0.0, 1.0)), nd.w / n, a.w > 0.0);
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn denoise_init(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
if (id.x >= Q.size.x || id.y >= Q.size.y) {
|
||||
return;
|
||||
}
|
||||
let i = id.y * Q.size.x + id.x;
|
||||
let g = guide(i);
|
||||
let h = acc_hit[i];
|
||||
let n = max(acc_alb[i].w, 1.0);
|
||||
let mean = h.rgb / n;
|
||||
let var_l = max(h.w / n - luminance(mean) * luminance(mean), 0.0) / n;
|
||||
let a = max(luminance(g.albedo), 0.02);
|
||||
dst[i] = vec4<f32>(mean / g.albedo, var_l / (a * a));
|
||||
}
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn denoise_step(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let w = Q.size.x;
|
||||
let h = Q.size.y;
|
||||
if (id.x >= w || id.y >= h) {
|
||||
return;
|
||||
}
|
||||
let i = id.y * w + id.x;
|
||||
let p = guide(i);
|
||||
let ip = src[i];
|
||||
if (!p.hit) {
|
||||
dst[i] = ip;
|
||||
return;
|
||||
}
|
||||
let step = i32(Q.size.w);
|
||||
var kernel = array<f32, 5>(1.0 / 16.0, 1.0 / 4.0, 3.0 / 8.0, 1.0 / 4.0, 1.0 / 16.0);
|
||||
let sigma_l = 4.0 * sqrt(ip.w) + 1e-3;
|
||||
var sum = vec3<f32>(0.0);
|
||||
var wsum = 0.0;
|
||||
var vsum = 0.0;
|
||||
for (var j = 0; j < 5; j++) {
|
||||
for (var k = 0; k < 5; k++) {
|
||||
let qx = i32(id.x) + (k - 2) * step;
|
||||
let qy = i32(id.y) + (j - 2) * step;
|
||||
if (qx < 0 || qy < 0 || qx >= i32(w) || qy >= i32(h)) {
|
||||
continue;
|
||||
}
|
||||
let qi = u32(qy) * w + u32(qx);
|
||||
let q = guide(qi);
|
||||
if (!q.hit) {
|
||||
continue;
|
||||
}
|
||||
let iq = src[qi];
|
||||
let wn = pow(max(dot(p.normal, q.normal), 0.0), 64.0);
|
||||
let wz = exp(-abs(p.depth - q.depth) / (0.01 * max(p.depth, 1e-3) * f32(step)));
|
||||
let wl = exp(-abs(luminance(ip.rgb) - luminance(iq.rgb)) / sigma_l);
|
||||
let wt = kernel[k] * kernel[j] * wn * wz * wl;
|
||||
sum += iq.rgb * wt;
|
||||
wsum += wt;
|
||||
vsum += wt * wt * iq.w;
|
||||
}
|
||||
}
|
||||
if (wsum > 1e-8) {
|
||||
dst[i] = vec4<f32>(sum / wsum, vsum / (wsum * wsum));
|
||||
} else {
|
||||
dst[i] = ip;
|
||||
}
|
||||
}
|
||||
|
||||
fn backdrop(uv: vec2<f32>) -> vec3<f32> {
|
||||
let r = length(uv * 2.0 - 1.0) * 0.35;
|
||||
return vec3<f32>(0.0232 * (1.06 - r * r));
|
||||
}
|
||||
|
||||
fn tonemap(hdr: vec3<f32>) -> vec3<f32> {
|
||||
let x = max(hdr, vec3<f32>(0.0)) * Q.display.x;
|
||||
if (Q.display.y < 0.5) {
|
||||
return min(x, vec3<f32>(1.0));
|
||||
}
|
||||
let v = x * 0.6;
|
||||
return clamp((v * (v * 2.51 + 0.03)) / (v * (v * 2.43 + 0.59) + 0.14), vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
}
|
||||
|
||||
fn to_srgb(c: vec3<f32>) -> vec3<f32> {
|
||||
let v = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - 0.055, v * 12.92, v <= vec3<f32>(0.0031308));
|
||||
}
|
||||
|
||||
// Display pixels: the mesh (denoised when `src` holds the filtered radiance) over the backdrop.
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn resolve(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
let w = Q.size.x;
|
||||
let h = Q.size.y;
|
||||
if (id.x >= w || id.y >= h) {
|
||||
return;
|
||||
}
|
||||
let i = id.y * w + id.x;
|
||||
let n = f32(max(Q.size.z, 1u));
|
||||
let uv = (vec2<f32>(id.xy) + 0.5) / vec2<f32>(f32(w), f32(h));
|
||||
let hits = acc_alb[i].w;
|
||||
let misses = n - hits;
|
||||
var back = backdrop(uv);
|
||||
if (misses > 0.0) {
|
||||
back = mix(back, tonemap(acc_env[i].rgb / misses), clamp(Q.display.z, 0.0, 1.0));
|
||||
}
|
||||
var mean = acc_hit[i].rgb / max(hits, 1.0);
|
||||
if (Q.display.w > 0.5) {
|
||||
mean = src[i].rgb * guide(i).albedo;
|
||||
}
|
||||
let scene = select(vec3<f32>(0.0), tonemap(mean), hits > 0.0);
|
||||
let c = mix(back, scene, hits / n);
|
||||
textureStore(out, vec2<i32>(id.xy), vec4<f32>(to_srgb(c), 1.0));
|
||||
}
|
||||
+188
-26
@@ -11,7 +11,11 @@
|
||||
//! scattering part of the diffuse light enters the mesh, scatters isotropically with the
|
||||
//! project's per-channel mean free path (no absorption: the base color tints it once, on entry)
|
||||
//! and leaves where the walk next crosses the surface, as a Lambertian emitter. Walks are capped
|
||||
//! at [`WALK_STEPS`] (their energy is dropped) and need closed meshes.
|
||||
//! at [`WALK_STEPS`] (their energy is dropped) and need closed meshes. The clear coat follows the
|
||||
//! Coat normal channel where a set has it. Transmission turns that part of the dielectric base
|
||||
//! into a rough glass interface: GGX visible-normal sampling, exact Fresnel at the project's IOR,
|
||||
//! refraction through the mesh (tinted by the base color on the way in). Depth of field comes from
|
||||
//! a thin-lens camera ([`TraceScene::lens`]).
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
use std::sync::Arc;
|
||||
@@ -44,17 +48,22 @@ pub struct TraceScene {
|
||||
/// Environment rotation around +Y (radians), as in the viewport.
|
||||
pub env_rotation: f32,
|
||||
/// Texture set per triangle (`usize::MAX`: none, default material).
|
||||
tri_set: Arc<Vec<usize>>,
|
||||
pub(crate) tri_set: Arc<Vec<usize>>,
|
||||
/// Importance sampling of the environment (None for an empty image).
|
||||
light: Option<Arc<EnvSampler>>,
|
||||
pub(crate) light: Option<Arc<EnvSampler>>,
|
||||
/// Specular/glossiness shading (Specular color is F0, base color is diffuse).
|
||||
pub spec_gloss: bool,
|
||||
/// Ray offset off surfaces, scaled to the mesh.
|
||||
eps: f32,
|
||||
pub(crate) eps: f32,
|
||||
/// Subsurface scattering extinction per color channel (1 / mean free path, world units).
|
||||
scatter_sigma: Vec3,
|
||||
/// Bounding radius of the mesh (scales the scatter radius).
|
||||
radius: f32,
|
||||
pub(crate) scatter_sigma: Vec3,
|
||||
/// Bounding radius of the mesh (scales the scatter radius and the lens).
|
||||
pub(crate) radius: f32,
|
||||
/// Index of refraction of the Transmission channel.
|
||||
pub ior: f32,
|
||||
/// Thin lens: focus depth along the view axis (0: the camera's orbit target) and lens radius
|
||||
/// as a fraction of the mesh's bounding radius (the viewport's depth of field).
|
||||
pub lens: Option<[f32; 2]>,
|
||||
}
|
||||
|
||||
impl TraceScene {
|
||||
@@ -75,8 +84,21 @@ impl TraceScene {
|
||||
let eps = ((hi - lo).length() * 2e-5).max(1e-6);
|
||||
let light = EnvSampler::new(&env).map(Arc::new);
|
||||
let radius = ((hi - lo).length() * 0.5).max(1e-6);
|
||||
let mut scene =
|
||||
TraceScene { mesh, bvh, sets, env, env_rotation, tri_set: Arc::new(tri_set), light, spec_gloss: false, eps, scatter_sigma: Vec3::ONE, radius };
|
||||
let mut scene = TraceScene {
|
||||
mesh,
|
||||
bvh,
|
||||
sets,
|
||||
env,
|
||||
env_rotation,
|
||||
tri_set: Arc::new(tri_set),
|
||||
light,
|
||||
spec_gloss: false,
|
||||
eps,
|
||||
scatter_sigma: Vec3::ONE,
|
||||
radius,
|
||||
ior: 1.5,
|
||||
lens: None,
|
||||
};
|
||||
let d = DisplaySettings::default();
|
||||
scene.set_scatter(d.scatter_color, d.scatter_radius);
|
||||
scene
|
||||
@@ -97,9 +119,31 @@ impl TraceScene {
|
||||
let mut scene = TraceScene::new(mesh, bvh, sets, Arc::new(env), display.env_rotation.to_radians());
|
||||
scene.spec_gloss = display.spec_gloss;
|
||||
scene.set_scatter(display.scatter_color, display.scatter_radius);
|
||||
scene.ior = display.ior;
|
||||
scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]);
|
||||
scene
|
||||
}
|
||||
|
||||
/// The camera ray through `ndc`, through a point of the lens when the scene has one.
|
||||
fn camera_ray(&self, cam: &OrbitCamera, ndc: Vec2, aspect: f32, rng: &mut Rng) -> texturecraft_geom::Ray {
|
||||
let ray = cam.ray(ndc, aspect);
|
||||
let Some([focus, aperture]) = self.lens else { return ray };
|
||||
let lens = aperture.max(0.0) * self.radius;
|
||||
let fwd = cam.forward();
|
||||
let along = ray.dir.dot(fwd);
|
||||
if lens <= 0.0 || along <= 1e-6 {
|
||||
return ray;
|
||||
}
|
||||
// The point this pixel sees on the focus plane, viewed from a random point of the lens.
|
||||
let depth = if focus > 0.0 { focus } else { cam.distance };
|
||||
let focal = ray.origin + ray.dir * ((depth - (ray.origin - cam.eye()).dot(fwd)) / along);
|
||||
let right = fwd.cross(Vec3::Y).normalize_or(Vec3::X);
|
||||
let up = right.cross(fwd);
|
||||
let (r, phi) = (lens * rng.next().sqrt(), TAU * rng.next());
|
||||
let origin = ray.origin + (right * phi.cos() + up * phi.sin()) * r;
|
||||
texturecraft_geom::Ray { origin, dir: (focal - origin).normalize_or(ray.dir) }
|
||||
}
|
||||
|
||||
/// World direction to environment space.
|
||||
fn to_env(&self, d: Vec3) -> Vec3 {
|
||||
let (s, c) = self.env_rotation.sin_cos();
|
||||
@@ -124,15 +168,15 @@ impl TraceScene {
|
||||
}
|
||||
|
||||
/// Piecewise-constant importance sampling of an equirect environment by luminance and sin(theta).
|
||||
struct EnvSampler {
|
||||
width: usize,
|
||||
height: usize,
|
||||
pub(crate) struct EnvSampler {
|
||||
pub(crate) width: usize,
|
||||
pub(crate) height: usize,
|
||||
/// Cumulative row probabilities (last = 1).
|
||||
rows: Vec<f32>,
|
||||
pub(crate) rows: Vec<f32>,
|
||||
/// Cumulative probabilities within each row (last of each row = 1).
|
||||
cols: Vec<f32>,
|
||||
pub(crate) cols: Vec<f32>,
|
||||
/// Probability of each pixel.
|
||||
prob: Vec<f32>,
|
||||
pub(crate) prob: Vec<f32>,
|
||||
}
|
||||
|
||||
impl EnvSampler {
|
||||
@@ -276,7 +320,7 @@ impl Tracer {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let mut rng = Rng::new(x as u32, y as u32, pass);
|
||||
let ndc = Vec2::new((x as f32 + rng.next()) / w as f32 * 2.0 - 1.0, 1.0 - (y as f32 + rng.next()) / h as f32 * 2.0);
|
||||
let ray = cam.ray(ndc, aspect);
|
||||
let ray = scene.camera_ray(cam, ndc, aspect, &mut rng);
|
||||
match trace(scene, ray.origin, ray.dir, settings, &mut rng) {
|
||||
Some(s) => {
|
||||
px.hit += s.radiance;
|
||||
@@ -452,6 +496,11 @@ struct Surface {
|
||||
sheen: Vec3,
|
||||
sheen_roughness: f32,
|
||||
scatter: f32,
|
||||
/// Transmissive part of the base, its tint (the base color), and whether the ray enters the
|
||||
/// mesh here (it hit the outside of the triangle).
|
||||
transmission: f32,
|
||||
base: Vec3,
|
||||
front: bool,
|
||||
}
|
||||
|
||||
fn lerp3(a: Vec3, b: Vec3, c: Vec3, u: f32, v: f32) -> Vec3 {
|
||||
@@ -473,7 +522,8 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3
|
||||
let mut geo = (p[1] - p[0]).cross(p[2] - p[0]).normalize_or(Vec3::Y);
|
||||
let nrm = idx.map(|k| m.normals.get(k).copied().unwrap_or(geo));
|
||||
let mut n_geo = lerp3(nrm[0], nrm[1], nrm[2], u, v).normalize_or(geo);
|
||||
if geo.dot(d) > 0.0 {
|
||||
let front = geo.dot(d) <= 0.0;
|
||||
if !front {
|
||||
geo = -geo;
|
||||
}
|
||||
if n_geo.dot(geo) < 0.0 {
|
||||
@@ -518,13 +568,22 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3
|
||||
Some(s) if s.composite.channels.contains_key(&Channel::Glossiness) => 1.0 - ch(Channel::Glossiness, 0, 0)[0],
|
||||
_ => ch(Channel::Roughness, 0, 0)[0],
|
||||
};
|
||||
let (diffuse, f0) = if scene.spec_gloss {
|
||||
let (diffuse, f0, metallic) = if scene.spec_gloss {
|
||||
let f0 = Vec3::from(ch(Channel::Specular, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE);
|
||||
(base * (1.0 - f0.max_element()), f0)
|
||||
(base * (1.0 - f0.max_element()), f0, 0.0)
|
||||
} else {
|
||||
let metallic = ch(Channel::Metallic, 0, 0)[0].clamp(0.0, 1.0);
|
||||
let level = ch(Channel::SpecularLevel, 0, 0)[0].clamp(0.0, 1.0);
|
||||
(base * (1.0 - metallic), Vec3::splat(0.08 * level).lerp(base, metallic))
|
||||
(base * (1.0 - metallic), Vec3::splat(0.08 * level).lerp(base, metallic), metallic)
|
||||
};
|
||||
let coat_base = if n_geo.dot(-d) > 0.0 { n_geo } else { geo };
|
||||
let coat_n = match set {
|
||||
Some(s) if s.composite.channels.contains_key(&Channel::CoatNormal) => {
|
||||
let c = (Vec3::from(ch(Channel::CoatNormal, 0, 0)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z);
|
||||
let turned = (tt * c.x + b * c.y + coat_base * c.z).normalize_or(coat_base);
|
||||
if turned.dot(-d) > 0.0 { turned } else { coat_base }
|
||||
}
|
||||
_ => coat_base,
|
||||
};
|
||||
Some(Surface {
|
||||
pos: o + d * t,
|
||||
@@ -539,10 +598,13 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3
|
||||
anisotropy: scalar(Channel::AnisotropyLevel),
|
||||
coat: scalar(Channel::CoatWeight),
|
||||
coat_roughness: scalar(Channel::CoatRoughness).max(0.045),
|
||||
coat_n: if n_geo.dot(-d) > 0.0 { n_geo } else { geo },
|
||||
coat_n,
|
||||
sheen: Vec3::from(ch(Channel::SheenColor, 0, 0)).clamp(Vec3::ZERO, Vec3::ONE) * scalar(Channel::SheenWeight),
|
||||
sheen_roughness: scalar(Channel::SheenRoughness).max(0.07),
|
||||
scatter: scalar(Channel::ScatterWeight),
|
||||
transmission: scalar(Channel::Transmission) * (1.0 - metallic),
|
||||
base: base.clamp(Vec3::ZERO, Vec3::ONE),
|
||||
front,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -783,6 +845,46 @@ impl Bsdf {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unpolarized Fresnel reflectance of a dielectric interface; `eta` = n(incident) / n(other side).
|
||||
fn fresnel_dielectric(cos_i: f32, eta: f32) -> f32 {
|
||||
let sin2_t = eta * eta * (1.0 - cos_i * cos_i).max(0.0);
|
||||
if sin2_t >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let cos_t = (1.0 - sin2_t).sqrt();
|
||||
let rs = (eta * cos_i - cos_t) / (eta * cos_i + cos_t);
|
||||
let rp = (cos_i - eta * cos_t) / (cos_i + eta * cos_t);
|
||||
0.5 * (rs * rs + rp * rp)
|
||||
}
|
||||
|
||||
/// Sampling density standing in for a lobe that next-event estimation never samples (its
|
||||
/// environment hits take the full MIS weight).
|
||||
const UNSAMPLED_PDF: f32 = 1e15;
|
||||
|
||||
/// The transmissive base as a rough dielectric interface (GGX, visible normals): reflect with
|
||||
/// the Fresnel at `ior`, else refract into (or out of) the mesh. Returns the new direction and the
|
||||
/// path weight (G1 of the new direction; the base color tints light entering the mesh).
|
||||
/// shortcut: radiance is not scaled by the squared IOR ratio at each crossing (the factors cancel
|
||||
/// for paths that leave the mesh again).
|
||||
fn dielectric(s: &Surface, v: Vec3, ior: f32, rng: &mut Rng) -> Option<(Vec3, Vec3)> {
|
||||
let a = (s.roughness * s.roughness).max(1e-3);
|
||||
let lobe = Ggx::new(s.tangent, s.n, v, a, a);
|
||||
let hl = sample_vndf(lobe.v, a, a, rng.next(), rng.next());
|
||||
let h = lobe.t * hl.x + lobe.b * hl.y + lobe.n * hl.z;
|
||||
let cos_i = v.dot(h).max(1e-6);
|
||||
let eta = if s.front { 1.0 / ior.max(1.0) } else { ior.max(1.0) };
|
||||
if rng.next() < fresnel_dielectric(cos_i, eta) {
|
||||
let l = h * 2.0 * cos_i - v;
|
||||
let ll = lobe.local(l);
|
||||
return (l.dot(s.geo) > 0.0 && ll.z > 0.0).then(|| (l, Vec3::splat(smith_g1(ll, a, a))));
|
||||
}
|
||||
let cos_t = (1.0 - eta * eta * (1.0 - cos_i * cos_i)).max(0.0).sqrt();
|
||||
let l = (h * (eta * cos_i - cos_t) - v * eta).normalize_or(-v);
|
||||
let ll = lobe.local(l);
|
||||
let tint = if s.front { s.base } else { Vec3::ONE };
|
||||
(l.dot(s.geo) < 0.0 && ll.z < 0.0).then(|| (l, tint * smith_g1(-ll, a, a)))
|
||||
}
|
||||
|
||||
/// Most scattering events a subsurface random walk takes before giving up.
|
||||
const WALK_STEPS: usize = 48;
|
||||
|
||||
@@ -876,14 +978,25 @@ fn trace(scene: &TraceScene, mut o: Vec3, mut d: Vec3, settings: &TraceSettings,
|
||||
if bounce >= settings.bounces {
|
||||
break;
|
||||
}
|
||||
// Transmission is picked by its weight (a glass event, without next-event estimation);
|
||||
// otherwise the surface shades as if it had none.
|
||||
let glass = s.transmission > 0.0 && rng.next() < s.transmission;
|
||||
let bsdf = Bsdf::new(&s, -d);
|
||||
// The BRDF is sampled with probability 1 − p_walk (densities below include that).
|
||||
let keep = 1.0 - bsdf.p_walk;
|
||||
l += next_event(scene, s.pos, s.geo, thr, rng, |wl| {
|
||||
let (f, pdf) = bsdf.eval(wl);
|
||||
(f, pdf * keep)
|
||||
});
|
||||
let (wi, geo) = if bsdf.p_walk > 0.0 && rng.next() < bsdf.p_walk {
|
||||
if !glass {
|
||||
l += next_event(scene, s.pos, s.geo, thr, rng, |wl| {
|
||||
let (f, pdf) = bsdf.eval(wl);
|
||||
(f, pdf * keep)
|
||||
});
|
||||
}
|
||||
let (wi, geo) = if glass {
|
||||
let Some((wi, w)) = dielectric(&s, -d, scene.ior, rng) else { break };
|
||||
thr *= w;
|
||||
brdf_pdf = Some(UNSAMPLED_PDF);
|
||||
o = s.pos;
|
||||
(wi, s.geo)
|
||||
} else if bsdf.p_walk > 0.0 && rng.next() < bsdf.p_walk {
|
||||
let Some((exit, out, w)) = random_walk(scene, &s, rng) else { break };
|
||||
thr *= bsdf.walk_albedo * w / bsdf.p_walk;
|
||||
// The light leaves the exit point like a Lambertian emitter.
|
||||
@@ -1163,4 +1276,53 @@ mod tests {
|
||||
let avg = sum / n as f32;
|
||||
assert!(avg.max_element() <= 1.05 && avg.min_element() > 0.3, "{avg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glass_white_furnace_stays_bounded() {
|
||||
for rough in [0.0, 0.3, 0.7] {
|
||||
let avg = furnace(&[(Channel::BaseColor, [1.0; 3]), (Channel::Roughness, [rough; 3]), (Channel::Transmission, [1.0; 3])]);
|
||||
assert!(avg.max_element() <= 1.05 && avg.min_element() > 0.5, "roughness {rough}: {avg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Mean radiance of the center ray from +z at the unit sphere, with an environment that is
|
||||
/// bright only behind the sphere (toward -z).
|
||||
fn behind_mean(values: &[(Channel, [f32; 3])]) -> Vec3 {
|
||||
let (w, h) = (64u32, 32u32);
|
||||
let data = (0..w * h)
|
||||
.map(|i| if crate::ibl::dir_of(((i % w) as f32 + 0.5) / w as f32, ((i / w) as f32 + 0.5) / h as f32).z < -0.7 { [5.0; 3] } else { [0.01; 3] })
|
||||
.collect();
|
||||
let s = material_scene(Arc::new(EnvImage { width: w, height: h, data }), values);
|
||||
let mut rng = Rng::new(3, 1, 4);
|
||||
let n = 2000;
|
||||
(0..n).map(|_| trace(&s, Vec3::new(0.0, 0.0, 4.0), Vec3::NEG_Z, &TraceSettings::default(), &mut rng).map_or(Vec3::ZERO, |s| s.radiance)).sum::<Vec3>()
|
||||
/ n as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmission_shows_the_environment_behind_the_mesh() {
|
||||
let white = [(Channel::BaseColor, [1.0; 3]), (Channel::Roughness, [0.05; 3])];
|
||||
let opaque = behind_mean(&white);
|
||||
let glass = behind_mean(&[white[0], white[1], (Channel::Transmission, [1.0; 3])]);
|
||||
assert!(glass.x > 2.0 && glass.x > 10.0 * opaque.x, "through the glass {glass}, opaque {opaque}");
|
||||
// The base color tints the light going through.
|
||||
let tinted = behind_mean(&[(Channel::BaseColor, [1.0, 0.2, 0.2]), white[1], (Channel::Transmission, [1.0; 3])]);
|
||||
assert!(tinted.x > 3.0 * tinted.y, "{tinted}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thin_lens_blurs_away_from_the_focus_plane() {
|
||||
// Pixels between the sphere and the backdrop: how soft the silhouette is.
|
||||
let soft_edge = |lens: Option<[f32; 2]>| {
|
||||
let s = TraceScene { lens, ..scene("Studio Soft") };
|
||||
let mut tr = Tracer::new(64, 48);
|
||||
for _ in 0..24 {
|
||||
tr.pass(&s, &camera(), &TraceSettings { bounces: 1 });
|
||||
}
|
||||
tr.acc.iter().filter(|p| p.hits > 2.0 && p.hits < tr.samples as f32 - 2.0).count()
|
||||
};
|
||||
let (pinhole, focused, blurred) = (soft_edge(None), soft_edge(Some([4.0 - 0.25, 0.1])), soft_edge(Some([20.0, 0.1])));
|
||||
assert!(blurred > 3 * pinhole.max(10), "out of focus: {pinhole} -> {blurred} edge pixels");
|
||||
assert!(focused < pinhole + pinhole / 2 + 10, "the silhouette (about the focus depth) stays sharp: {pinhole} -> {focused}");
|
||||
}
|
||||
}
|
||||
@@ -248,6 +248,13 @@ fn bench_1080p() {
|
||||
});
|
||||
println!("everything: {:.3} ms/frame", run(&mut h, &all));
|
||||
println!("parallax occlusion: {:.3} ms/frame", run(&mut h, &shaded(&frame, |s| s.parallax = true)));
|
||||
println!("depth of field: {:.3} ms/frame", run(&mut h, &shaded(&frame, |s| s.dof = Some([0.0, 0.1]))));
|
||||
println!("subsurface blur: {:.3} ms/frame", run(&mut h, &shaded(&frame, |s| s.sss_blur = Some([0.1, 0.04, 0.025]))));
|
||||
let both = shaded(&frame, |s| {
|
||||
s.dof = Some([0.0, 0.1]);
|
||||
s.sss_blur = Some([0.1, 0.04, 0.025]);
|
||||
});
|
||||
println!("depth of field + subsurface blur: {:.3} ms/frame", run(&mut h, &both));
|
||||
// Every extra lobe painted (full-size lobe textures), with the key light.
|
||||
fill_res(&mut h, 2048, &[0, 1], DisplayKind::Lobes, &[255, 25, 200, 60]);
|
||||
fill_res(&mut h, 2048, &[0, 1], DisplayKind::Sheen, &[200, 150, 255, 200]);
|
||||
@@ -426,8 +433,9 @@ fn lobe_channels_at_their_defaults_change_nothing() {
|
||||
fill(&mut h, &[0, 1], DisplayKind::Lobes, &[255, 200, 255, 90]);
|
||||
fill(&mut h, &[0, 1], DisplayKind::Sheen, &[255, 0, 0, 255]);
|
||||
fill(&mut h, &[0, 1], DisplayKind::Emissive, &[0, 0, 0, 255]);
|
||||
fill(&mut h, &[0, 1], DisplayKind::Extra, &[255, 0, 255, 0]);
|
||||
assert_ne!(render(&mut h, &lit, "lobes_painted").px, base.px);
|
||||
for k in [DisplayKind::Lobes, DisplayKind::Sheen, DisplayKind::Emissive] {
|
||||
for k in [DisplayKind::Lobes, DisplayKind::Sheen, DisplayKind::Emissive, DisplayKind::Extra] {
|
||||
fill(&mut h, &[0, 1], k, &k.default_texel());
|
||||
}
|
||||
assert_eq!(render(&mut h, &lit, "lobes_defaults").px, base.px);
|
||||
@@ -502,3 +510,136 @@ fn subsurface_scattering_softens_the_terminator() {
|
||||
assert!(luma(&skin, &bright) - luma(&skin, &dark) < luma(&lambert, &bright) - luma(&lambert, &dark), "contrast drops");
|
||||
assert!(warm(&skin) > warm(&lambert) + 2.0, "the scatter color tints the falloff ({} -> {})", warm(&lambert), warm(&skin));
|
||||
}
|
||||
|
||||
// ---- Transmission, coat normal, depth of field, subsurface blur --------------------------------
|
||||
|
||||
/// A base color checker (8-texel squares) on both sets, for detail to blur.
|
||||
fn checker(h: &mut Headless) {
|
||||
for ts in 0..2 {
|
||||
for (tx, ty) in (0..16).map(|i| (i % 4, i / 4)) {
|
||||
let bytes: Vec<u8> =
|
||||
(0..64 * 64).flat_map(|i| if ((i % 64) / 8 + (i / 64) / 8) % 2 == 0 { [230, 230, 230, 255] } else { [20, 20, 20, 255] }).collect();
|
||||
h.renderer.upload_tile(&h.device, &h.queue, ts, DisplayKind::BaseColor, tx, ty, &bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Σ|∂luma/∂x| over `mask`: how much detail the image shows there.
|
||||
fn detail(img: &Img, mask: &[bool]) -> f32 {
|
||||
(0..mask.len())
|
||||
.filter(|i| mask[*i] && i % 480 < 479 && mask[i + 1])
|
||||
.map(|i| (img.luma(i as u32 % 480 + 1, i as u32 / 480) - img.luma(i as u32 % 480, i as u32 / 480)).abs())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Mean |luma difference| over a square of side 2r around (x, y).
|
||||
fn patch_diff(a: &Img, b: &Img, (x, y): (u32, u32), r: u32) -> f32 {
|
||||
let mut sum = 0.0;
|
||||
for yy in y - r..y + r {
|
||||
for xx in x - r..x + r {
|
||||
sum += (a.luma(xx, yy) - b.luma(xx, yy)).abs();
|
||||
}
|
||||
}
|
||||
sum / (4 * r * r) as f32
|
||||
}
|
||||
|
||||
/// View depth of the mesh under the view's center pixel.
|
||||
fn center_depth(frame: &Frame) -> f32 {
|
||||
let mesh = primitives::material_ball();
|
||||
let bvh = texturecraft_geom::Bvh::new(&mesh);
|
||||
let cam = frame.camera;
|
||||
let ray = cam.ray(texturecraft_geom::glam::Vec2::ZERO, frame.size[0] as f32 / frame.size[1] as f32);
|
||||
let hit = bvh.closest(ray.origin, ray.dir, f32::MAX).expect("the ball is in the middle");
|
||||
(ray.origin + ray.dir * hit.t - cam.eye()).dot(cam.forward())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_of_field_blurs_away_from_the_focus_plane() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let mask = mesh_mask(&mut h, &frame, &[0, 1]);
|
||||
checker(&mut h);
|
||||
let sharp = render(&mut h, &frame, "dof_off");
|
||||
let dof = |focus: f32, aperture: f32| shaded(&frame, |s| s.dof = Some([focus, aperture]));
|
||||
assert_eq!(render(&mut h, &dof(0.0, 0.0), "dof_pinhole").px, sharp.px, "a pinhole lens changes nothing");
|
||||
let z = center_depth(&frame);
|
||||
let focused = render(&mut h, &dof(z, 0.15), "dof_focused");
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
assert!(patch_diff(&focused, &sharp, center, 5) < 3.0, "the focus plane stays sharp: {}", patch_diff(&focused, &sharp, center, 5));
|
||||
let far = render(&mut h, &dof(z * 10.0, 0.3), "dof_far_focus");
|
||||
let (d_sharp, d_far) = (detail(&sharp, &mask), detail(&far, &mask));
|
||||
assert!(d_far < 0.5 * d_sharp, "out of focus, the checker blurs: detail {d_sharp} -> {d_far}");
|
||||
assert!(patch_diff(&far, &sharp, center, 5) > 5.0);
|
||||
// Focused on the ball, it keeps more of its detail than focused far behind it.
|
||||
assert!(detail(&focused, &mask) > d_far);
|
||||
// Idle accumulation averages frames with the sampling spiral turned each time.
|
||||
let taa = shaded(&dof(z * 10.0, 0.3), |s| s.taa = true);
|
||||
assert_eq!(render(&mut h, &taa, "dof_taa_first").px, far.px, "the first sample is the plain frame");
|
||||
for _ in 1..TAA_SAMPLES {
|
||||
render(&mut h, &taa, "dof_taa_sample");
|
||||
}
|
||||
assert!(!h.renderer.accumulating(1));
|
||||
assert_ne!(render(&mut h, &taa, "dof_taa_converged").px, far.px);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subsurface_blur_spreads_only_scattering_light() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let lit = shaded(&frame, |s| s.light = LIGHT);
|
||||
let mask = mesh_mask(&mut h, &lit, &[0, 1]);
|
||||
checker(&mut h);
|
||||
let plain = render(&mut h, &lit, "sss_blur_off");
|
||||
let blur = shaded(&lit, |s| s.sss_blur = Some([0.06, 0.024, 0.015]));
|
||||
assert_eq!(render(&mut h, &blur, "sss_blur_no_weight").px, plain.px, "nothing scatters without the scattering weight");
|
||||
fill(&mut h, &[0, 1], DisplayKind::Emissive, &[0, 0, 0, 255]);
|
||||
let wrap = render(&mut h, &lit, "sss_wrap_only");
|
||||
let blurred = render(&mut h, &blur, "sss_blur_on");
|
||||
let (d0, d1) = (detail(&wrap, &mask), detail(&blurred, &mask));
|
||||
assert!(d1 < 0.85 * d0, "the scattering light blurs the checker: detail {d0} -> {d1}");
|
||||
// On a plain color the blur only moves light around the smooth shading (the checker's mean
|
||||
// display value rises: averaging happens before the sRGB curve).
|
||||
fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[150, 150, 150, 255]);
|
||||
let mean = |img: &Img| region_mean(&mask, |x, y| img.luma(x, y));
|
||||
let (m0, m1) = (mean(&render(&mut h, &lit, "sss_plain_wrap")), mean(&render(&mut h, &blur, "sss_plain_blur")));
|
||||
assert!((m1 - m0).abs() < 2.0, "the blur moves light, it adds none: {m0} -> {m1}");
|
||||
}
|
||||
|
||||
/// An environment that is bright only around `dir` (world space, rotation 0).
|
||||
fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes {
|
||||
let (w, hh) = (256u32, 128u32);
|
||||
let rgba = (0..w * hh)
|
||||
.map(|i| {
|
||||
let d = texturecraft_render::ibl::dir_of(((i % w) as f32 + 0.5) / w as f32, ((i / w) as f32 + 0.5) / hh as f32);
|
||||
if d.dot(dir) > 0.5 { [6.0, 6.0, 6.0, 1.0] } else { [0.02, 0.02, 0.02, 1.0] }
|
||||
})
|
||||
.collect();
|
||||
ImageRes { width: w, height: hh, rgba, srgb: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmission_shows_the_environment_behind_the_surface() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
h.renderer.set_environment(&h.device, &h.queue, "resource:behind.hdr", Some(&spot_environment(frame.camera.forward())));
|
||||
fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[255, 255, 255, 255]);
|
||||
fill(&mut h, &[0, 1], DisplayKind::Orm, &[255, 10, 0, 128]);
|
||||
let center = (frame.size[0] / 2, frame.size[1] / 2);
|
||||
let opaque = render(&mut h, &frame, "glass_off");
|
||||
fill(&mut h, &[0, 1], DisplayKind::Extra, &[128, 128, 255, 0]);
|
||||
let glass = render(&mut h, &frame, "glass_on");
|
||||
let luma = |img: &Img| img.mean(center.0 - 4, center.1 - 4, center.0 + 4, center.1 + 4);
|
||||
assert!(luma(&glass) > luma(&opaque) + 60.0, "the bright environment behind shows through: {} -> {}", luma(&opaque), luma(&glass));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coat_normal_turns_the_coat_reflection() {
|
||||
let Some((mut h, frame)) = setup() else { return };
|
||||
let lit = shaded(&frame, |s| s.light = LIGHT);
|
||||
let mask = mesh_mask(&mut h, &lit, &[0, 1]);
|
||||
fill(&mut h, &[0, 1], DisplayKind::Lobes, &[255, 13, 0, 0]);
|
||||
let flat = render(&mut h, &lit, "coat_normal_flat");
|
||||
fill(&mut h, &[0, 1], DisplayKind::Extra, &[128, 128, 0, 0]);
|
||||
assert_eq!(render(&mut h, &lit, "coat_normal_default").px, flat.px, "the flat coat normal is exact");
|
||||
fill(&mut h, &[0, 1], DisplayKind::Extra, &[230, 128, 0, 0]);
|
||||
let tilted = render(&mut h, &lit, "coat_normal_tilted");
|
||||
let diff = region_mean(&mask, |x, y| (tilted.luma(x, y) - flat.luma(x, y)).abs());
|
||||
assert!(diff > 2.0, "a tilted coat normal moves the coat highlight: {diff}");
|
||||
}
|
||||
+58
-49
@@ -236,62 +236,71 @@ impl TileImage {
|
||||
if self.allocated_count() == 0 {
|
||||
return out;
|
||||
}
|
||||
let (sw, sh) = (self.width as f32, self.height as f32);
|
||||
let (dw, dh) = (out.width, out.height);
|
||||
let comps = self.comps;
|
||||
for ty in 0..out.tiles_y {
|
||||
for tx in 0..out.tiles_x {
|
||||
// Skip destination tiles whose source footprint has no allocated tile.
|
||||
let (x0, y0) = ((tx * TILE) as f32 * sw / dw as f32, (ty * TILE) as f32 * sh / dh as f32);
|
||||
let (x1, y1) = (((tx + 1) * TILE) as f32 * sw / dw as f32, ((ty + 1) * TILE) as f32 * sh / dh as f32);
|
||||
let any = ((y0 as u32).saturating_sub(1) / TILE..=((y1 as u32 + 1) / TILE).min(self.tiles_y.saturating_sub(1)))
|
||||
.any(|sy| ((x0 as u32).saturating_sub(1) / TILE..=((x1 as u32 + 1) / TILE).min(self.tiles_x.saturating_sub(1))).any(|sx| self.is_allocated(sx, sy)));
|
||||
if !any {
|
||||
continue;
|
||||
if let Some(data) = self.resampled_tile(width, height, tx, ty, empty) {
|
||||
out.set_tile(tx, ty, Some(Arc::new(data)));
|
||||
}
|
||||
let mut data = vec![0u16; TILE_AREA * comps];
|
||||
for ly in 0..TILE {
|
||||
let y = ty * TILE + ly;
|
||||
if y >= dh {
|
||||
break;
|
||||
}
|
||||
let fy = ((y as f32 + 0.5) * sh / dh as f32 - 0.5).max(0.0);
|
||||
let (iy, wy) = (fy.floor() as u32, fy.fract());
|
||||
for lx in 0..TILE {
|
||||
let x = tx * TILE + lx;
|
||||
if x >= dw {
|
||||
break;
|
||||
}
|
||||
let fx = ((x as f32 + 0.5) * sw / dw as f32 - 0.5).max(0.0);
|
||||
let (ix, wx) = (fx.floor() as u32, fx.fract());
|
||||
let get = |x: u32, y: u32| {
|
||||
let (x, y) = (x.min(self.width - 1), y.min(self.height - 1));
|
||||
if self.is_allocated(x / TILE, y / TILE) {
|
||||
self.get(x, y)
|
||||
} else {
|
||||
let mut e = [0u16; 4];
|
||||
for (d, s) in e.iter_mut().zip(empty) {
|
||||
*d = *s;
|
||||
}
|
||||
e
|
||||
}
|
||||
};
|
||||
let (a, b, c, d) = (get(ix, iy), get(ix + 1, iy), get(ix, iy + 1), get(ix + 1, iy + 1));
|
||||
let o = ((ly * TILE + lx) as usize) * comps;
|
||||
for k in 0..comps {
|
||||
let top = a[k] as f32 * (1.0 - wx) + b[k] as f32 * wx;
|
||||
let bot = c[k] as f32 * (1.0 - wx) + d[k] as f32 * wx;
|
||||
if let Some(slot) = data.get_mut(o + k) {
|
||||
*slot = (top * (1.0 - wy) + bot * wy + 0.5) as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.set_tile(tx, ty, Some(Arc::new(data)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Tile (tx, ty) of [`TileImage::resampled`] alone (None when its source footprint is
|
||||
/// entirely unallocated).
|
||||
pub fn resampled_tile(&self, width: u32, height: u32, tx: u32, ty: u32, empty: &[u16]) -> Option<Vec<u16>> {
|
||||
let (sw, sh) = (self.width as f32, self.height as f32);
|
||||
let (dw, dh) = (width.max(1), height.max(1));
|
||||
let comps = self.comps;
|
||||
// Skip destination tiles whose source footprint has no allocated tile.
|
||||
let (x0, y0) = ((tx * TILE) as f32 * sw / dw as f32, (ty * TILE) as f32 * sh / dh as f32);
|
||||
let (x1, y1) = (((tx + 1) * TILE) as f32 * sw / dw as f32, ((ty + 1) * TILE) as f32 * sh / dh as f32);
|
||||
let any = ((y0 as u32).saturating_sub(1) / TILE..=((y1 as u32 + 1) / TILE).min(self.tiles_y.saturating_sub(1))).any(|sy| {
|
||||
((x0 as u32).saturating_sub(1) / TILE..=((x1 as u32 + 1) / TILE).min(self.tiles_x.saturating_sub(1))).any(|sx| self.is_allocated(sx, sy))
|
||||
});
|
||||
if !any || self.width == 0 || self.height == 0 {
|
||||
return None;
|
||||
}
|
||||
let get = |x: u32, y: u32| {
|
||||
let (x, y) = (x.min(self.width - 1), y.min(self.height - 1));
|
||||
if self.is_allocated(x / TILE, y / TILE) {
|
||||
self.get(x, y)
|
||||
} else {
|
||||
let mut e = [0u16; 4];
|
||||
for (d, s) in e.iter_mut().zip(empty) {
|
||||
*d = *s;
|
||||
}
|
||||
e
|
||||
}
|
||||
};
|
||||
let mut data = vec![0u16; TILE_AREA * comps];
|
||||
for ly in 0..TILE {
|
||||
let y = ty * TILE + ly;
|
||||
if y >= dh {
|
||||
break;
|
||||
}
|
||||
let fy = ((y as f32 + 0.5) * sh / dh as f32 - 0.5).max(0.0);
|
||||
let (iy, wy) = (fy.floor() as u32, fy.fract());
|
||||
for lx in 0..TILE {
|
||||
let x = tx * TILE + lx;
|
||||
if x >= dw {
|
||||
break;
|
||||
}
|
||||
let fx = ((x as f32 + 0.5) * sw / dw as f32 - 0.5).max(0.0);
|
||||
let (ix, wx) = (fx.floor() as u32, fx.fract());
|
||||
let (a, b, c, d) = (get(ix, iy), get(ix + 1, iy), get(ix, iy + 1), get(ix + 1, iy + 1));
|
||||
let o = ((ly * TILE + lx) as usize) * comps;
|
||||
for k in 0..comps {
|
||||
let top = a[k] as f32 * (1.0 - wx) + b[k] as f32 * wx;
|
||||
let bot = c[k] as f32 * (1.0 - wx) + d[k] as f32 * wx;
|
||||
if let Some(slot) = data.get_mut(o + k) {
|
||||
*slot = (top * (1.0 - wy) + bot * wy + 0.5) as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(data)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+214
-76
@@ -4,9 +4,12 @@
|
||||
use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{BakedMap, BlendMode, Channel, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source};
|
||||
use texturecraft_engine::core::{
|
||||
BakedMap, BlendMode, Channel, Decal, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, ProceduralKind, Source,
|
||||
};
|
||||
use texturecraft_engine::filter_lib::{FILTERS, scalar_params};
|
||||
use texturecraft_engine::paint::{BrushAlpha, alphas};
|
||||
use texturecraft_engine::{StackTarget, Tool};
|
||||
use texturecraft_engine::{CloneFrom, StackTarget, Tool};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::shelf::{Asset, ShelfDrag};
|
||||
@@ -150,12 +153,16 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
app.run("layer.move", json!({"layer": *dragged, "index": 0}));
|
||||
}
|
||||
}
|
||||
if let Some(d) = dnd_release::<ShelfDrag>(&resp)
|
||||
&& let Asset::Material(m) = d.asset
|
||||
{
|
||||
app.run("material.apply", json!({"material": m, "index": 0}));
|
||||
match dnd_release::<ShelfDrag>(&resp).map(|d| d.asset.clone()) {
|
||||
Some(Asset::Material(m)) => {
|
||||
app.run("material.apply", json!({"material": m, "index": 0}));
|
||||
}
|
||||
Some(Asset::Library(path)) => {
|
||||
app.run("material.load", json!({"path": path, "index": 0}));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let material = resp.dnd_hover_payload::<ShelfDrag>().is_some_and(|d| matches!(d.asset, Asset::Material(_)));
|
||||
let material = resp.dnd_hover_payload::<ShelfDrag>().is_some_and(|d| d.asset.is_material());
|
||||
if resp.dnd_hover_payload::<u64>().is_some() || material {
|
||||
ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, TOKENS.accent));
|
||||
}
|
||||
@@ -164,7 +171,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
|
||||
/// Whether the selection targets the layer content (the content or one of its effects) rather
|
||||
/// than the mask.
|
||||
fn targets_content(app: &TextureCraftApp) -> bool {
|
||||
pub(crate) fn targets_content(app: &TextureCraftApp) -> bool {
|
||||
let p = &app.session.doc.project;
|
||||
match app.session.target {
|
||||
StackTarget::Content => true,
|
||||
@@ -185,24 +192,36 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
("Add paint", "effect.add.paint", json!({"target": t})),
|
||||
("Add fill", "effect.add.fill", json!({"target": t})),
|
||||
("Add levels", "effect.add.levels", json!({"target": t})),
|
||||
("Add filter: blur", "effect.add.filter", json!({"target": t, "filter": "blur", "radius": 8})),
|
||||
("Add filter: sharpen", "effect.add.filter", json!({"target": t, "filter": "sharpen"})),
|
||||
("Add filter: invert", "effect.add.filter", json!({"target": t, "filter": "invert"})),
|
||||
("Add filter: threshold", "effect.add.filter", json!({"target": t, "filter": "threshold"})),
|
||||
("Add filter: HSL", "effect.add.filter", json!({"target": t, "filter": "hsl"})),
|
||||
("Add compare mask", "effect.add.compare", json!({})),
|
||||
("Add anchor point", "effect.add.anchor", json!({})),
|
||||
];
|
||||
let run = |app: &mut TextureCraftApp, id: &str, p: &Value| {
|
||||
if app.session.selected_layer() != Some(layer.id) {
|
||||
app.run("layer.select", json!({"layer": layer.id.0}));
|
||||
}
|
||||
app.run(id, with(p, json!({"layer": layer.id.0})));
|
||||
};
|
||||
for (label, id, p) in items {
|
||||
let enabled = id != "effect.add.anchor" || !layer.is_group();
|
||||
if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
|
||||
if app.session.selected_layer() != Some(layer.id) {
|
||||
app.run("layer.select", json!({"layer": layer.id.0}));
|
||||
}
|
||||
app.run(id, with(&p, json!({"layer": layer.id.0})));
|
||||
run(app, id, &p);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
// The filter library (material finishes only fill content).
|
||||
ui.menu_button("Add filter", |ui| {
|
||||
let mut group = "";
|
||||
for f in FILTERS.iter().filter(|f| content || f.mask) {
|
||||
if f.group != group {
|
||||
ui.label(caption(f.group));
|
||||
group = f.group;
|
||||
}
|
||||
if ui.button(f.label).clicked() {
|
||||
run(app, "effect.add.filter", &json!({"target": t, "filter": f.id}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) {
|
||||
@@ -416,9 +435,9 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
// Drops: a layer or a shelf material lands above this row (inside a folder when dropped on
|
||||
// its middle); a shelf smart mask replaces this layer's mask.
|
||||
let inside = layer.is_group() && ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| (p.y - rect.center().y).abs() < h * 0.25);
|
||||
let shelf = resp.dnd_hover_payload::<ShelfDrag>().map(|d| d.asset);
|
||||
let shelf = resp.dnd_hover_payload::<ShelfDrag>().map(|d| d.asset.clone());
|
||||
let moving = resp.dnd_hover_payload::<u64>().is_some_and(|src| *src != layer.id.0);
|
||||
if moving || matches!(shelf, Some(Asset::Material(_))) {
|
||||
if moving || shelf.as_ref().is_some_and(Asset::is_material) {
|
||||
if inside {
|
||||
p.rect_stroke(rect, 2.0, Stroke::new(2.0, TOKENS.accent), egui::StrokeKind::Inside);
|
||||
} else {
|
||||
@@ -426,20 +445,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize
|
||||
}
|
||||
} else if matches!(shelf, Some(Asset::SmartMask(_))) {
|
||||
p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(2.0, TOKENS.accent), egui::StrokeKind::Outside);
|
||||
} else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() {
|
||||
p.rect_stroke(rect, 2.0, Stroke::new(2.0, TOKENS.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
if let Some(src) = dnd_release::<u64>(&resp)
|
||||
&& *src != layer.id.0
|
||||
{
|
||||
app.run("layer.move", json!({"layer": *src, "above": layer.id.0, "inside": inside}));
|
||||
}
|
||||
match dnd_release::<ShelfDrag>(&resp).map(|d| d.asset) {
|
||||
match dnd_release::<ShelfDrag>(&resp).map(|d| d.asset.clone()) {
|
||||
Some(Asset::Material(m)) => {
|
||||
app.run("material.apply", json!({"material": m, "above": layer.id.0, "inside": inside}));
|
||||
}
|
||||
Some(Asset::Library(path)) => {
|
||||
app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside}));
|
||||
}
|
||||
Some(Asset::SmartMask(m)) => {
|
||||
app.run("mask.smart.apply", json!({"name": m, "layer": layer.id.0}));
|
||||
}
|
||||
Some(Asset::Alpha(_)) | None => {}
|
||||
Some(Asset::Filter(f)) => {
|
||||
app.run("layer.select", json!({"layer": layer.id.0}));
|
||||
app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": f, "target": "content"}));
|
||||
}
|
||||
Some(Asset::Alpha(_) | Asset::Texture(_)) | None => {}
|
||||
}
|
||||
resp.context_menu(|ui| layer_context_menu(app, ui, layer));
|
||||
}
|
||||
@@ -571,7 +599,8 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.end_row();
|
||||
if !set.uv_tiles.is_empty() {
|
||||
ui.label("UV tiles");
|
||||
ui.label(set.uv_tiles.iter().map(u32::to_string).collect::<Vec<_>>().join(", ")).on_hover_text("UDIM tiles painted by this texture set, each at the set's size");
|
||||
ui.label(set.uv_tiles.iter().map(u32::to_string).collect::<Vec<_>>().join(", "))
|
||||
.on_hover_text("UDIM tiles painted by this texture set, each at the set's size");
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label("Shader instance");
|
||||
@@ -815,6 +844,17 @@ fn import_button(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
|
||||
fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(caption("Clone"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Copy from");
|
||||
for (mode, label, tip, id) in [
|
||||
(CloneFrom::Composite, "All layers", "Copy what the texture set shows", "composite"),
|
||||
(CloneFrom::Layer, "Current layer", "Copy the selected layer alone (its empty parts copy nothing)", "layer"),
|
||||
] {
|
||||
if chip(ui, label, app.session.tool.clone_from == mode).on_hover_text(tip).clicked() {
|
||||
app.run("tool.brush", json!({"cloneSource": id}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let Some(src) = app.session.tool.clone_source else {
|
||||
ui.label(RichText::new("Hold V and click the mesh to set the source, then paint elsewhere to copy it.").color(TOKENS.text_dim));
|
||||
return;
|
||||
@@ -990,7 +1030,7 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
app.run("tool.brush", json!({ "alpha": alpha }));
|
||||
}
|
||||
ui.label(RichText::new("More in Assets > Alphas: click one, or drag it here").size(10.0).color(TOKENS.text_dim));
|
||||
crate::shelf::drop_target(app, ui, &zone.response, false);
|
||||
crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush);
|
||||
}
|
||||
|
||||
fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
@@ -1085,8 +1125,37 @@ fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> Str
|
||||
/// its enabled channels) or a content fill effect's (`base` = {"effect"}, `on` = the channels
|
||||
/// it has a source for). `reader` is the layer owning the fill (for anchor sources).
|
||||
fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) {
|
||||
use texturecraft_engine::core::{ChannelKind, Projection};
|
||||
use texturecraft_engine::core::Projection;
|
||||
let salt = base.to_string();
|
||||
if let Projection::Decal(d) = &fill.projection {
|
||||
decal_editor(app, ui, d, reader);
|
||||
} else {
|
||||
projection_editor(app, ui, fill, base);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.label(caption("Material"));
|
||||
let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for c in &chans {
|
||||
let enabled = on.contains(c);
|
||||
if chip(ui, c.short(), enabled).clicked() {
|
||||
app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": !enabled})));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let anchors = anchors_below(app, reader);
|
||||
for c in chans {
|
||||
if !on.contains(&c) {
|
||||
continue;
|
||||
}
|
||||
fill_channel(app, ui, fill, base, c, &anchors, &salt);
|
||||
}
|
||||
}
|
||||
|
||||
/// The projection of a fill (other than a decal): kind and scale.
|
||||
fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) {
|
||||
use texturecraft_engine::core::Projection;
|
||||
let proj_label = fill.projection.label();
|
||||
egui::ComboBox::from_label("Projection").selected_text(proj_label).show_ui(ui, |ui| {
|
||||
for (id, label) in [
|
||||
@@ -1107,27 +1176,50 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value
|
||||
Projection::Planar { scale, .. } => (*scale, "planar"),
|
||||
Projection::Spherical { scale } => (*scale, "spherical"),
|
||||
Projection::Cylindrical { scale, .. } => (*scale, "cylindrical"),
|
||||
Projection::Decal(_) => return,
|
||||
};
|
||||
if slider(ui, "Scale / tiling", &mut scale, 0.01..=20.0, 2).drag_stopped() {
|
||||
app.run("layer.fill.projection", with(base, json!({"projection": proj_id, "scale": scale})));
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
ui.label(caption("Material"));
|
||||
let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for c in &chans {
|
||||
let enabled = on.contains(c);
|
||||
if chip(ui, c.short(), enabled).clicked() {
|
||||
app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": !enabled})));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let anchors = anchors_below(app, reader);
|
||||
for c in chans {
|
||||
if !on.contains(&c) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
/// A decal's frame: place it with a click in the 3D view, then size, turn and shift it.
|
||||
fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerId) {
|
||||
ui.label(caption("Decal"));
|
||||
let placing = app.placing_decal == Some(layer);
|
||||
let label = if placing { format!("{} Click the mesh to place the decal", ic::CROSSHAIR) } else { format!("{} Place on the surface", ic::CROSSHAIR) };
|
||||
if ui.selectable_label(placing, label).on_hover_text("The next click in the 3D view moves the decal there").clicked() {
|
||||
app.placing_decal = if placing { None } else { Some(layer) };
|
||||
}
|
||||
let (lo, hi) = app.session.mesh.bounds();
|
||||
let diag = (hi - lo).length().max(1e-3);
|
||||
let mut v = [d.size[0], d.size[1], d.rotation, d.offset[0], d.offset[1], d.depth];
|
||||
let rows = [
|
||||
("Width", diag * 0.01..=diag * 2.0),
|
||||
("Height", diag * 0.01..=diag * 2.0),
|
||||
("Rotation (degrees)", 0.0..=360.0),
|
||||
("Offset right", -diag..=diag),
|
||||
("Offset up", -diag..=diag),
|
||||
("Depth", diag * 0.005..=diag),
|
||||
];
|
||||
let mut done = false;
|
||||
for ((label, range), x) in rows.into_iter().zip(v.iter_mut()) {
|
||||
done |= slider(ui, label, x, range, 3).drag_stopped();
|
||||
}
|
||||
if done {
|
||||
app.run("layer.decal.set", json!({"layer": layer.0, "size": [v[0], v[1]], "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5]}));
|
||||
}
|
||||
ui.label(
|
||||
RichText::new("The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.")
|
||||
.size(10.5)
|
||||
.color(TOKENS.text_dim),
|
||||
);
|
||||
}
|
||||
|
||||
/// The source of one fill channel: uniform, procedural, image or anchor.
|
||||
fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, c: Channel, anchors: &[(LayerId, String)], salt: &str) {
|
||||
use texturecraft_engine::core::ChannelKind;
|
||||
{
|
||||
let set = |extra: Value| with(base, with(&json!({"channel": c.id()}), extra));
|
||||
ui.group(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
@@ -1153,7 +1245,7 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value
|
||||
if !anchors.is_empty() {
|
||||
ui.separator();
|
||||
}
|
||||
for (a, label) in &anchors {
|
||||
for (a, label) in anchors {
|
||||
if ui.button(format!("Anchor: {label}")).clicked() {
|
||||
app.run("layer.fill.set", set(json!({"anchor": a.0})));
|
||||
ui.close();
|
||||
@@ -1187,7 +1279,10 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value
|
||||
let mut seed = pattern.seed as f32;
|
||||
let r3 = slider(ui, "Seed", &mut seed, 0.0..=999.0, 0);
|
||||
if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() {
|
||||
app.run("layer.fill.set", set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high})));
|
||||
app.run(
|
||||
"layer.fill.set",
|
||||
set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high})),
|
||||
);
|
||||
}
|
||||
if c.kind() == ChannelKind::Color {
|
||||
let (mut lo, mut hi) = (low, high);
|
||||
@@ -1199,7 +1294,10 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value
|
||||
changed |= color_swatch(ui, &format!("hi_{salt}_{}", c.id()), &mut hi, 60.0);
|
||||
});
|
||||
if changed {
|
||||
app.run("layer.fill.set", set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": pattern.seed, "low": lo, "high": hi})));
|
||||
app.run(
|
||||
"layer.fill.set",
|
||||
set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": pattern.seed, "low": lo, "high": hi})),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1330,44 +1428,84 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
);
|
||||
}
|
||||
EffectKind::Paint => {
|
||||
let what = if layer.content_effects.iter().any(|x| x.id == eid) { "the layer content" } else { "this mask. Use the Material tab's mask value for gray" };
|
||||
let what =
|
||||
if layer.content_effects.iter().any(|x| x.id == eid) { "the layer content" } else { "this mask. Use the Material tab's mask value for gray" };
|
||||
ui.label(RichText::new(format!("Paint on the mesh to edit {what}.")).color(TOKENS.text_dim));
|
||||
tool_properties(app, ui);
|
||||
}
|
||||
EffectKind::Filter(Filter::Hsl { hue, saturation, lightness }) => {
|
||||
ui.label(caption("HSL"));
|
||||
let (mut h, mut s, mut l) = (hue * 360.0, *saturation, *lightness);
|
||||
let r1 = slider(ui, "Hue shift (degrees)", &mut h, -180.0..=180.0, 0);
|
||||
let r2 = slider(ui, "Saturation", &mut s, -1.0..=1.0, 2);
|
||||
let r3 = slider(ui, "Lightness", &mut l, -1.0..=1.0, 2);
|
||||
if r1.drag_stopped() || r2.drag_stopped() || r3.drag_stopped() {
|
||||
app.run("effect.set", json!({"effect": id, "hue": h / 360.0, "saturation": s, "lightness": l}));
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(Filter::Blur { radius }) => {
|
||||
ui.label(caption("Blur"));
|
||||
let mut r = *radius;
|
||||
if slider(ui, "Intensity (texels at 2K)", &mut r, 0.0..=128.0, 1).drag_stopped() {
|
||||
app.run("effect.set", json!({"effect": id, "radius": r}));
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(Filter::Sharpen { amount }) => {
|
||||
ui.label(caption("Sharpen"));
|
||||
let mut a = *amount;
|
||||
if slider(ui, "Amount", &mut a, 0.0..=5.0, 2).drag_stopped() {
|
||||
app.run("effect.set", json!({"effect": id, "amount": a}));
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(Filter::Threshold { level }) => {
|
||||
ui.label(caption("Threshold"));
|
||||
let mut l = *level;
|
||||
if slider(ui, "Level", &mut l, 0.0..=1.0, 2).drag_stopped() {
|
||||
app.run("effect.set", json!({"effect": id, "level": l}));
|
||||
}
|
||||
}
|
||||
EffectKind::Filter(f) => filter_properties(app, ui, id, f),
|
||||
other => {
|
||||
ui.label(RichText::new(other.name()).color(TOKENS.text_dim));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of filter effect `id`.
|
||||
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) {
|
||||
let set = |app: &mut TextureCraftApp, key: &str, v: Value| {
|
||||
let mut p = json!({ "effect": id });
|
||||
p[key] = v;
|
||||
app.run("effect.set", p);
|
||||
};
|
||||
ui.label(caption(f.label()));
|
||||
if let Filter::Hsl { hue, .. } = f {
|
||||
let mut h = hue * 360.0;
|
||||
if slider(ui, "Hue shift (degrees)", &mut h, -180.0..=180.0, 0).drag_stopped() {
|
||||
set(app, "hue", json!(h / 360.0));
|
||||
}
|
||||
}
|
||||
for (key, label, mut v, lo, hi) in scalar_params(f) {
|
||||
let decimals = if matches!(key, "seed" | "levels") {
|
||||
0
|
||||
} else if hi - lo > 10.0 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
if slider(ui, label, &mut v, lo..=hi, decimals).drag_stopped() {
|
||||
set(app, key, json!(v));
|
||||
}
|
||||
}
|
||||
match f {
|
||||
Filter::ColorBalance { shadows, midtones, highlights } => {
|
||||
for (key, label, rgb) in [("shadows", "Shadows", shadows), ("midtones", "Midtones", midtones), ("highlights", "Highlights", highlights)] {
|
||||
ui.label(RichText::new(label).strong());
|
||||
let mut v = *rgb;
|
||||
let mut done = false;
|
||||
for (x, name) in v.iter_mut().zip(["Cyan / red", "Magenta / green", "Yellow / blue"]) {
|
||||
done |= slider(ui, name, x, -1.0..=1.0, 2).drag_stopped();
|
||||
}
|
||||
if done {
|
||||
set(app, key, json!(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
Filter::GradientMap { colors } => {
|
||||
let mut c = colors.clone();
|
||||
let mut changed = false;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (i, col) in c.iter_mut().enumerate() {
|
||||
changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0);
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} Add color", ic::PLUS))).clicked() {
|
||||
c.push(c.last().copied().unwrap_or([1.0; 3]));
|
||||
changed = true;
|
||||
}
|
||||
if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} Remove last", ic::MINUS))).clicked() {
|
||||
c.pop();
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if changed {
|
||||
set(app, "colors", json!(c));
|
||||
}
|
||||
ui.label(RichText::new("Dark to light: the content's luminance picks a color along these stops.").size(10.5).color(TOKENS.text_dim));
|
||||
}
|
||||
Filter::Warp { .. } | Filter::DirectionalBlur { .. } | Filter::SlopeBlur { .. } => {
|
||||
ui.label(RichText::new("Works in texture space, like the blur: it does not cross UV seams.").size(10.5).color(TOKENS.text_dim));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,8 @@ pub struct TextureCraftApp {
|
||||
pub profiler: profile::Profiler,
|
||||
/// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines.
|
||||
pub last_paint_point: Option<texturecraft_engine::geom::glam::Vec2>,
|
||||
/// The decal layer the next click in the 3D view places.
|
||||
pub placing_decal: Option<texturecraft_engine::core::LayerId>,
|
||||
/// The wgpu state (screenshots read the renderer's targets).
|
||||
pub render_state: Option<eframe::egui_wgpu::RenderState>,
|
||||
last_time: f64,
|
||||
@@ -105,6 +107,7 @@ impl TextureCraftApp {
|
||||
library: None,
|
||||
render: render_mode::RenderView::default(),
|
||||
last_paint_point: None,
|
||||
placing_decal: None,
|
||||
render_state: cc.wgpu_render_state.clone(),
|
||||
last_time: 0.0,
|
||||
next_autosave,
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
//! Rendering mode (F10): a progressive path-traced view of the current camera. The tracer runs on
|
||||
//! a worker thread (one pass per frame on the single-threaded web) and restarts whenever the
|
||||
//! scene, camera, view size or settings change.
|
||||
//! Rendering mode (F10): a progressive path-traced view of the current camera, restarted whenever
|
||||
//! the scene, camera, view size or settings change.
|
||||
//!
|
||||
//! Where the device has compute shaders (desktop, WebGPU) it traces on the GPU: the tracer lives in
|
||||
//! egui's callback resources next to the viewport renderer (whose texture sets it copies), a paint
|
||||
//! callback adds samples each frame and resolves into a texture egui shows as it is, so nothing is
|
||||
//! read back until the render is saved. Otherwise (WebGL2, the CPU setting, or a GPU error) the CPU
|
||||
//! tracer runs on a worker thread (one slice per frame on the single-threaded web).
|
||||
|
||||
use std::sync::Arc;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
|
||||
use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor};
|
||||
use egui::{Color32, ColorImage, Rect, RichText, TextureHandle, TextureOptions, Ui, vec2};
|
||||
use texturecraft_engine::geom::OrbitCamera;
|
||||
use texturecraft_render::gpu_trace::GpuTracer;
|
||||
use texturecraft_render::readback::Readback;
|
||||
use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer};
|
||||
use texturecraft_render::{Renderer, wgpu};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::theme::TOKENS;
|
||||
@@ -71,7 +80,7 @@ impl Work {
|
||||
}
|
||||
}
|
||||
|
||||
/// The running render of one scene state.
|
||||
/// The running CPU render of one scene state.
|
||||
struct Job {
|
||||
key: String,
|
||||
latest: Arc<Mutex<Option<Frame>>>,
|
||||
@@ -89,23 +98,72 @@ impl Drop for Job {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the GPU callback reports back to the UI.
|
||||
#[derive(Default)]
|
||||
struct GpuStatus {
|
||||
samples: u32,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// "Save render..." on the GPU: the copy of the shown render on its way to the CPU.
|
||||
#[derive(Default)]
|
||||
enum Read {
|
||||
#[default]
|
||||
Idle,
|
||||
/// The next callback copies the render.
|
||||
Wanted,
|
||||
/// Copied in a submitted frame: map it.
|
||||
Copied(Readback),
|
||||
Mapping(Readback),
|
||||
}
|
||||
|
||||
/// The GPU render shown in the view.
|
||||
struct GpuView {
|
||||
size: (u32, u32),
|
||||
/// What [`GpuView::scene`] was built from (everything but the camera, size and settings).
|
||||
scene_key: String,
|
||||
scene: Arc<TraceScene>,
|
||||
/// The restart key of the samples counted in `status`.
|
||||
key: String,
|
||||
started: f64,
|
||||
out: wgpu::Texture,
|
||||
out_view: wgpu::TextureView,
|
||||
texture: egui::TextureId,
|
||||
status: Arc<Mutex<GpuStatus>>,
|
||||
/// Samples per pixel per frame: grows while frames are quick, halves when they are slow.
|
||||
spp: u32,
|
||||
read: Arc<Mutex<Read>>,
|
||||
}
|
||||
|
||||
/// The GPU tracer in egui's callback resources.
|
||||
struct TraceState {
|
||||
tracer: GpuTracer,
|
||||
scene: Option<Arc<TraceScene>>,
|
||||
key: String,
|
||||
/// Samples in the resolved image (None: resolve again).
|
||||
resolved: Option<u32>,
|
||||
}
|
||||
|
||||
/// Rendering mode state kept by the app.
|
||||
#[derive(Default)]
|
||||
pub struct RenderView {
|
||||
job: Option<Job>,
|
||||
gpu: Option<GpuView>,
|
||||
/// Why the GPU tracer failed on the scene of this key (the CPU renders it instead).
|
||||
gpu_error: Option<(String, String)>,
|
||||
texture: Option<TextureHandle>,
|
||||
shown: Option<(u32, u32, Vec<u8>)>,
|
||||
samples: u32,
|
||||
elapsed: f64,
|
||||
}
|
||||
|
||||
/// Viewport resolution of the render (the web renders at half size: it has one thread).
|
||||
/// Viewport resolution of a CPU render (the web renders at half size: it has one thread).
|
||||
fn render_size(rect: Rect) -> (u32, u32) {
|
||||
let scale = if cfg!(target_arch = "wasm32") { 0.5 } else { 1.0 };
|
||||
((rect.width() * scale).max(16.0) as u32, (rect.height() * scale).max(16.0) as u32)
|
||||
}
|
||||
|
||||
fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work {
|
||||
fn trace_scene(app: &TextureCraftApp) -> TraceScene {
|
||||
let s = &app.session;
|
||||
let d = &s.doc.project.display;
|
||||
let sets = s
|
||||
@@ -117,21 +175,38 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work {
|
||||
.map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() })
|
||||
.collect();
|
||||
let env_image = d.environment_resource().and_then(|n| s.images.get(n));
|
||||
TraceScene::for_display(s.mesh.clone(), s.bvh.clone(), sets, d, env_image.map(|i| i.as_ref()))
|
||||
}
|
||||
|
||||
fn settings(app: &TextureCraftApp) -> TraceSettings {
|
||||
TraceSettings { bounces: app.ui.render.bounces }
|
||||
}
|
||||
|
||||
fn display(app: &TextureCraftApp) -> TraceDisplay {
|
||||
TraceDisplay { denoise: app.ui.render.denoise, ..TraceDisplay::from_display(&app.session.doc.project.display) }
|
||||
}
|
||||
|
||||
fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work {
|
||||
Work {
|
||||
scene: TraceScene::for_display(s.mesh.clone(), s.bvh.clone(), sets, d, env_image.map(|i| i.as_ref())),
|
||||
camera: s.camera,
|
||||
settings: TraceSettings { bounces: app.ui.render.bounces },
|
||||
display: TraceDisplay { denoise: app.ui.render.denoise, ..TraceDisplay::from_display(d) },
|
||||
scene: trace_scene(app),
|
||||
camera: app.session.camera,
|
||||
settings: settings(app),
|
||||
display: display(app),
|
||||
max_samples: app.ui.render.max_samples.max(1),
|
||||
tracer: Tracer::new(size.0, size.1),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the render depends on; a change restarts it.
|
||||
fn key(app: &TextureCraftApp, size: (u32, u32)) -> String {
|
||||
/// What the traced scene depends on.
|
||||
fn scene_key(app: &TextureCraftApp) -> String {
|
||||
let s = &app.session;
|
||||
let revisions: Vec<u64> = s.caches.iter().map(|c| c.revision).collect();
|
||||
format!("{}|{revisions:?}|{:?}|{size:?}|{:?}|{:?}", s.mesh_id, s.camera, s.doc.project.display, app.ui.render)
|
||||
format!("{}|{revisions:?}|{:?}", s.mesh_id, s.doc.project.display)
|
||||
}
|
||||
|
||||
/// What the render depends on; a change restarts it.
|
||||
fn key(app: &TextureCraftApp, size: (u32, u32)) -> String {
|
||||
format!("{}|{:?}|{size:?}|{:?}", scene_key(app), app.session.camera, app.ui.render)
|
||||
}
|
||||
|
||||
fn start(app: &TextureCraftApp, ctx: &egui::Context, key: String, size: (u32, u32)) -> Job {
|
||||
@@ -166,6 +241,15 @@ fn start(app: &TextureCraftApp, ctx: &egui::Context, key: String, size: (u32, u3
|
||||
|
||||
/// Draw Rendering mode over the 3D view in `rect` (navigation is handled by the 3D view).
|
||||
pub fn show(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) {
|
||||
let on_gpu = !app.ui.render.cpu && show_gpu(app, ui, rect);
|
||||
if !on_gpu {
|
||||
drop_gpu(app);
|
||||
show_cpu(app, ui, rect);
|
||||
}
|
||||
overlay(app, ui, rect, on_gpu);
|
||||
}
|
||||
|
||||
fn show_cpu(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let size = render_size(rect);
|
||||
let k = key(app, size);
|
||||
@@ -174,7 +258,6 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) {
|
||||
app.render.samples = 0;
|
||||
}
|
||||
let now = ctx.input(|i| i.time);
|
||||
let mut running = false;
|
||||
if let Some(job) = app.render.job.as_mut() {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
@@ -195,31 +278,276 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) {
|
||||
app.render.elapsed = now - job.started;
|
||||
app.render.shown = Some((f.width, f.height, f.rgba));
|
||||
}
|
||||
running = app.render.samples < app.ui.render.max_samples;
|
||||
}
|
||||
let shown = app.render.texture.as_ref().filter(|_| app.render.samples > 0).map(TextureHandle::id);
|
||||
paint(ui, rect, shown);
|
||||
}
|
||||
|
||||
/// The render, or a placeholder until its first samples.
|
||||
fn paint(ui: &Ui, rect: Rect, texture: Option<egui::TextureId>) {
|
||||
let p = ui.painter_at(rect);
|
||||
match &app.render.texture {
|
||||
Some(t) if app.render.samples > 0 => {
|
||||
p.image(t.id(), rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
match texture {
|
||||
Some(t) => {
|
||||
p.image(t, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
_ => {
|
||||
None => {
|
||||
p.rect_filled(rect, 0.0, TOKENS.viewport);
|
||||
p.text(rect.center(), egui::Align2::CENTER_CENTER, "Starting render...", egui::FontId::proportional(14.0), TOKENS.text_dim);
|
||||
}
|
||||
}
|
||||
overlay(app, ui, rect, running);
|
||||
}
|
||||
|
||||
/// Trace on the GPU; false when it can't (no compute shaders, or it failed on this scene).
|
||||
fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool {
|
||||
let Some(rs) = app.render_state.clone() else { return false };
|
||||
let scene_key = scene_key(app);
|
||||
if !GpuTracer::supported(&rs.device) || app.render.gpu_error.as_ref().is_some_and(|(k, _)| *k == scene_key) {
|
||||
return false;
|
||||
}
|
||||
app.render.gpu_error = None;
|
||||
if app.render.job.take().is_some() {
|
||||
app.render.texture = None;
|
||||
app.render.shown = None;
|
||||
}
|
||||
let ctx = ui.ctx().clone();
|
||||
let now = ctx.input(|i| i.time);
|
||||
let size = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32);
|
||||
let key = key(app, size);
|
||||
let mut g = match app.render.gpu.take() {
|
||||
Some(g) if g.size == size => g,
|
||||
old => {
|
||||
let out = GpuTracer::output_texture(&rs.device, size.0, size.1);
|
||||
let out_view = out.create_view(&Default::default());
|
||||
// A resized view keeps its scene and egui texture id.
|
||||
let (texture, scene_key, scene) = match old {
|
||||
Some(old) => {
|
||||
rs.renderer.write().update_egui_texture_from_wgpu_texture(&rs.device, &out_view, wgpu::FilterMode::Linear, old.texture);
|
||||
(old.texture, old.scene_key, old.scene)
|
||||
}
|
||||
None => (
|
||||
rs.renderer.write().register_native_texture(&rs.device, &out_view, wgpu::FilterMode::Linear),
|
||||
scene_key.clone(),
|
||||
Arc::new(trace_scene(app)),
|
||||
),
|
||||
};
|
||||
GpuView { size, scene_key, scene, key: String::new(), started: now, out, out_view, texture, status: Arc::default(), spp: 1, read: Arc::default() }
|
||||
}
|
||||
};
|
||||
let (samples, error) = {
|
||||
let mut st = g.status.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if g.key != key {
|
||||
st.samples = 0;
|
||||
}
|
||||
(st.samples, st.error.take())
|
||||
};
|
||||
if let Some(e) = error {
|
||||
log::warn!("GPU path tracing failed, rendering on the CPU: {e}");
|
||||
app.render.gpu_error = Some((scene_key, e));
|
||||
app.render.gpu = Some(g);
|
||||
return false;
|
||||
}
|
||||
if g.key != key {
|
||||
g.key = key.clone();
|
||||
g.started = now;
|
||||
}
|
||||
if g.scene_key != scene_key {
|
||||
g.scene = Arc::new(trace_scene(app));
|
||||
g.scene_key = scene_key;
|
||||
}
|
||||
let max_samples = app.ui.render.max_samples.max(1);
|
||||
if samples < max_samples {
|
||||
// Keep the UI near 60 fps: more samples while frames are quick, half as many when slow.
|
||||
let dt = ctx.input(|i| i.stable_dt);
|
||||
g.spp = if dt > 1.0 / 40.0 {
|
||||
(g.spp / 2).max(1)
|
||||
} else if dt < 1.0 / 60.0 {
|
||||
(g.spp + 1).min(16)
|
||||
} else {
|
||||
g.spp
|
||||
};
|
||||
app.render.elapsed = now - g.started;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
app.render.samples = samples;
|
||||
if poll_read(app, &rs.device, &g) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
let cb = TraceCallback {
|
||||
key,
|
||||
scene: g.scene.clone(),
|
||||
camera: app.session.camera,
|
||||
settings: settings(app),
|
||||
display: display(app),
|
||||
max_samples,
|
||||
spp: g.spp,
|
||||
size,
|
||||
out: g.out.clone(),
|
||||
out_view: g.out_view.clone(),
|
||||
status: g.status.clone(),
|
||||
read: g.read.clone(),
|
||||
};
|
||||
ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, cb));
|
||||
paint(ui, rect, (samples > 0).then_some(g.texture));
|
||||
app.render.gpu = Some(g);
|
||||
true
|
||||
}
|
||||
|
||||
/// Advance "Save render..." on the GPU: map the copy once its frame was submitted, then save.
|
||||
/// True while it is pending.
|
||||
fn poll_read(app: &mut TextureCraftApp, device: &wgpu::Device, g: &GpuView) -> bool {
|
||||
let mut read = g.read.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let pixels = match std::mem::take(&mut *read) {
|
||||
Read::Copied(r) => {
|
||||
r.map();
|
||||
*read = Read::Mapping(r);
|
||||
None
|
||||
}
|
||||
Read::Mapping(r) => {
|
||||
// Runs map callbacks on native backends (the browser runs them on its own).
|
||||
let _ = device.poll(wgpu::PollType::Poll);
|
||||
match r.take() {
|
||||
Some(px) => Some(px),
|
||||
None => {
|
||||
*read = Read::Mapping(r);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
other => {
|
||||
*read = other;
|
||||
None
|
||||
}
|
||||
};
|
||||
let pending = !matches!(*read, Read::Idle);
|
||||
drop(read);
|
||||
match pixels {
|
||||
Some(Some(px)) => {
|
||||
app.render.shown = Some(px);
|
||||
save(app);
|
||||
}
|
||||
Some(None) => app.toast("Couldn't read the render back from the GPU", true),
|
||||
None => {}
|
||||
}
|
||||
pending
|
||||
}
|
||||
|
||||
/// Adds samples on the GPU and resolves them into the shown texture.
|
||||
struct TraceCallback {
|
||||
key: String,
|
||||
scene: Arc<TraceScene>,
|
||||
camera: OrbitCamera,
|
||||
settings: TraceSettings,
|
||||
display: TraceDisplay,
|
||||
max_samples: u32,
|
||||
spp: u32,
|
||||
size: (u32, u32),
|
||||
out: wgpu::Texture,
|
||||
out_view: wgpu::TextureView,
|
||||
status: Arc<Mutex<GpuStatus>>,
|
||||
read: Arc<Mutex<Read>>,
|
||||
}
|
||||
|
||||
impl TraceCallback {
|
||||
fn run(
|
||||
&self,
|
||||
st: &mut TraceState,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
renderer: &Renderer,
|
||||
) -> Result<(), String> {
|
||||
let t = &mut st.tracer;
|
||||
if !st.scene.as_ref().is_some_and(|s| Arc::ptr_eq(s, &self.scene)) {
|
||||
t.set_scene(device, queue, &self.scene)?;
|
||||
st.scene = Some(self.scene.clone());
|
||||
}
|
||||
if t.sync_materials(device, queue, encoder, renderer)? || st.key != self.key {
|
||||
t.reset(device, encoder, self.size.0, self.size.1)?;
|
||||
st.key.clone_from(&self.key);
|
||||
st.resolved = None;
|
||||
}
|
||||
let done = t.samples();
|
||||
if done < self.max_samples {
|
||||
t.pass(device, queue, encoder, &self.camera, &self.settings, self.spp.min(self.max_samples - done));
|
||||
}
|
||||
if st.resolved != Some(t.samples()) {
|
||||
t.resolve(device, queue, encoder, &self.display, &self.out_view);
|
||||
st.resolved = Some(t.samples());
|
||||
}
|
||||
let mut read = self.read.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if matches!(*read, Read::Wanted) {
|
||||
*read = Read::Copied(Readback::new(device, encoder, &self.out));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTrait for TraceCallback {
|
||||
fn prepare(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
_screen: &ScreenDescriptor,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
resources: &mut CallbackResources,
|
||||
) -> Vec<wgpu::CommandBuffer> {
|
||||
let state = match resources.remove::<TraceState>() {
|
||||
Some(st) => Ok(st),
|
||||
None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None }),
|
||||
};
|
||||
let result = state.and_then(|mut st| {
|
||||
let r = match resources.get::<crate::gpu::GpuState>() {
|
||||
Some(gpu) => self.run(&mut st, device, queue, encoder, &gpu.renderer),
|
||||
None => Err("the viewport renderer is missing".into()),
|
||||
};
|
||||
let samples = st.tracer.samples();
|
||||
resources.insert(st);
|
||||
r.map(|()| samples)
|
||||
});
|
||||
let mut status = self.status.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match result {
|
||||
Ok(samples) => status.samples = samples,
|
||||
Err(e) => status.error = Some(e),
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn paint(&self, _info: egui::PaintCallbackInfo, _pass: &mut wgpu::RenderPass<'static>, _resources: &CallbackResources) {}
|
||||
}
|
||||
|
||||
/// Free the GPU render (its texture and the tracer's scene memory; the pipelines stay).
|
||||
fn drop_gpu(app: &mut TextureCraftApp) {
|
||||
let Some(g) = app.render.gpu.take() else { return };
|
||||
if let Some(rs) = &app.render_state {
|
||||
let mut r = rs.renderer.write();
|
||||
r.free_texture(&g.texture);
|
||||
if let Some(st) = r.callback_resources.get_mut::<TraceState>() {
|
||||
st.tracer.release();
|
||||
(st.scene, st.resolved) = (None, None);
|
||||
st.key.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The render status and settings card in the top-left corner.
|
||||
fn overlay(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, running: bool) {
|
||||
let card = Rect::from_min_size(rect.min + vec2(12.0, 12.0), vec2(250.0, 176.0));
|
||||
fn overlay(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, on_gpu: bool) {
|
||||
let card = Rect::from_min_size(rect.min + vec2(12.0, 12.0), vec2(250.0, 200.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(card).layout(egui::Layout::top_down(egui::Align::Min)));
|
||||
egui::Frame::popup(child.style()).show(&mut child, |ui| {
|
||||
ui.set_width(226.0);
|
||||
let max = app.ui.render.max_samples.max(1);
|
||||
let running = app.render.samples < max;
|
||||
ui.label(RichText::new("RENDERING").size(11.0).strong());
|
||||
let status = if running { "Rendering" } else { "Done" };
|
||||
ui.label(RichText::new(format!("{status}: {} / {max} samples, {:.1} s", app.render.samples, app.render.elapsed)).size(11.0).color(TOKENS.text_dim));
|
||||
let device = if on_gpu { "GPU" } else { "CPU" };
|
||||
let line = ui.label(
|
||||
RichText::new(format!("{status} on {device}: {} / {max} samples, {:.1} s", app.render.samples, app.render.elapsed))
|
||||
.size(11.0)
|
||||
.color(TOKENS.text_dim),
|
||||
);
|
||||
if let Some((_, e)) = app.render.gpu_error.as_ref().filter(|_| !on_gpu && !app.ui.render.cpu) {
|
||||
line.on_hover_text(format!("The GPU couldn't render this scene: {e}"));
|
||||
}
|
||||
ui.add(egui::ProgressBar::new(app.render.samples as f32 / max as f32).desired_height(4.0));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Samples");
|
||||
@@ -228,9 +556,17 @@ fn overlay(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, running: bool) {
|
||||
ui.add(egui::DragValue::new(&mut app.ui.render.bounces).range(1..=32));
|
||||
});
|
||||
ui.checkbox(&mut app.ui.render.denoise, "Denoise").on_hover_text("Filter the remaining noise while keeping edges and texture detail");
|
||||
if app.render_state.as_ref().is_some_and(|rs| GpuTracer::supported(&rs.device)) {
|
||||
ui.checkbox(&mut app.ui.render.cpu, "Render on the CPU").on_hover_text("Path trace on the processor instead of the graphics card (slower)");
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(app.render.shown.is_some(), egui::Button::new("Save render...")).clicked() {
|
||||
save(app);
|
||||
let saving = app.render.gpu.as_ref().is_some_and(|g| !matches!(*g.read.lock().unwrap_or_else(PoisonError::into_inner), Read::Idle));
|
||||
let ready = if on_gpu { app.render.samples > 0 && !saving } else { app.render.shown.is_some() };
|
||||
if ui.add_enabled(ready, egui::Button::new("Save render...")).clicked() {
|
||||
match app.render.gpu.as_ref().filter(|_| on_gpu) {
|
||||
Some(g) => *g.read.lock().unwrap_or_else(PoisonError::into_inner) = Read::Wanted,
|
||||
None => save(app),
|
||||
}
|
||||
}
|
||||
if ui.button("Back to painting").clicked() {
|
||||
app.ui.mode = crate::state::Mode::Painting;
|
||||
@@ -264,11 +600,12 @@ fn save(app: &mut TextureCraftApp) {
|
||||
|
||||
impl RenderView {
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.job.is_some() || self.texture.is_some()
|
||||
self.job.is_some() || self.gpu.is_some() || self.texture.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop rendering (leaving Rendering mode frees the worker and the image).
|
||||
/// Stop rendering (leaving Rendering mode frees the worker, the GPU memory and the image).
|
||||
pub fn stop(app: &mut TextureCraftApp) {
|
||||
drop_gpu(app);
|
||||
app.render = RenderView::default();
|
||||
}
|
||||
+118
-36
@@ -1,12 +1,14 @@
|
||||
//! The asset shelf (the Assets dock tab): Painter-style tabs (materials, smart materials, smart
|
||||
//! masks, alphas, procedurals, environments, textures), all built in and procedural. Search
|
||||
//! filters across every tab. Materials, smart masks and alphas drag onto the layer stack, a
|
||||
//! layer row, the viewport or the brush properties ([`ShelfDrag`]).
|
||||
//! masks, filters, alphas, procedurals, environments, textures), all built in and procedural.
|
||||
//! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas
|
||||
//! and textures drag onto the layer stack, a layer row, the viewport or the brush properties
|
||||
//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there.
|
||||
|
||||
use egui::{Color32, RichText, Sense, Stroke, Ui, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::ProceduralKind;
|
||||
use texturecraft_engine::filter_lib::FILTERS;
|
||||
use texturecraft_engine::materials::MATERIALS;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
use texturecraft_engine::smart_masks::SMART_MASKS;
|
||||
@@ -21,67 +23,105 @@ enum Tab {
|
||||
Materials,
|
||||
Smart,
|
||||
Masks,
|
||||
Filters,
|
||||
Alphas,
|
||||
Procedurals,
|
||||
Environments,
|
||||
Textures,
|
||||
}
|
||||
|
||||
const TABS: [(Tab, &str, &str); 7] = [
|
||||
const TABS: [(Tab, &str, &str); 8] = [
|
||||
(Tab::Materials, ic::SPHERE, "Materials"),
|
||||
(Tab::Smart, ic::STACK, "Smart materials"),
|
||||
(Tab::Masks, ic::CIRCLE_HALF, "Smart masks"),
|
||||
(Tab::Filters, ic::FUNNEL, "Filters"),
|
||||
(Tab::Alphas, ic::SHAPES, "Alphas"),
|
||||
(Tab::Procedurals, ic::CHECKERBOARD, "Procedurals"),
|
||||
(Tab::Environments, ic::SUN_HORIZON, "Environments"),
|
||||
(Tab::Textures, ic::IMAGE, "Textures"),
|
||||
];
|
||||
|
||||
/// A built-in asset (by id).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
/// A shelf asset: built in (by id), a saved smart material (file path) or an image resource.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Asset {
|
||||
Material(&'static str),
|
||||
SmartMask(&'static str),
|
||||
Filter(&'static str),
|
||||
Alpha(&'static str),
|
||||
Library(String),
|
||||
Texture(String),
|
||||
}
|
||||
|
||||
impl Asset {
|
||||
/// Assets that add layers (built-in and saved smart materials).
|
||||
pub fn is_material(&self) -> bool {
|
||||
matches!(self, Asset::Material(_) | Asset::Library(_))
|
||||
}
|
||||
}
|
||||
|
||||
/// The drag-and-drop payload of a shelf tile.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ShelfDrag {
|
||||
pub asset: Asset,
|
||||
pub label: &'static str,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// Apply `asset` the way a shelf click does: a material above the selection, a smart mask on
|
||||
/// the selected layer, an alpha on the brush.
|
||||
pub fn apply(app: &mut TextureCraftApp, asset: Asset) {
|
||||
/// the selected layer, a filter on the selection (its mask when the mask is selected), an alpha
|
||||
/// on the brush, a texture as an image fill.
|
||||
pub fn apply(app: &mut TextureCraftApp, asset: &Asset) {
|
||||
let (cmd, params) = match asset {
|
||||
Asset::Material(id) => ("material.apply", json!({"material": id})),
|
||||
Asset::SmartMask(id) => ("mask.smart.apply", json!({"name": id})),
|
||||
Asset::Filter(id) => ("effect.add.filter", json!({"filter": id, "target": if crate::dock::targets_content(app) { "content" } else { "mask" }})),
|
||||
Asset::Alpha(id) => ("tool.brush", json!({"alpha": {"library": id}})),
|
||||
Asset::Library(path) => ("material.load", json!({"path": path})),
|
||||
Asset::Texture(name) => ("layer.add.image", json!({"name": name})),
|
||||
};
|
||||
app.run(cmd, params);
|
||||
}
|
||||
|
||||
/// Make `resp` (the viewport, or the brush properties when `materials` is false) a drop target
|
||||
/// for shelf alphas and materials: outline it while one hovers, apply it on release.
|
||||
pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, materials: bool) {
|
||||
let accepts = |d: &ShelfDrag| matches!(d.asset, Asset::Alpha(_)) || (materials && matches!(d.asset, Asset::Material(_)));
|
||||
/// What a view accepts from the shelf.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DropZone {
|
||||
/// The brush properties: alphas.
|
||||
Brush,
|
||||
/// The 2D view: alphas and materials.
|
||||
View2d,
|
||||
/// The 3D view: alphas, materials and textures (placed as decals where they drop).
|
||||
View3d,
|
||||
}
|
||||
|
||||
/// Make `resp` a drop target for shelf assets `zone` accepts: outline it while one hovers,
|
||||
/// apply it on release.
|
||||
pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, zone: DropZone) {
|
||||
let accepts = |d: &ShelfDrag| match d.asset {
|
||||
Asset::Alpha(_) => true,
|
||||
Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush,
|
||||
Asset::Texture(_) => zone == DropZone::View3d,
|
||||
Asset::SmartMask(_) | Asset::Filter(_) => false,
|
||||
};
|
||||
if resp.dnd_hover_payload::<ShelfDrag>().is_some_and(|d| accepts(&d)) {
|
||||
ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, TOKENS.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
let pointer = ui.input(|i| i.pointer.interact_pos());
|
||||
if let Some(d) = dnd_release::<ShelfDrag>(resp)
|
||||
&& accepts(&d)
|
||||
{
|
||||
apply(app, d.asset);
|
||||
match (&d.asset, pointer) {
|
||||
(Asset::Texture(name), Some(p)) => {
|
||||
let (q, vp) = (p - resp.rect.min, resp.rect.size());
|
||||
app.run("layer.add.decal", json!({"image": name, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}));
|
||||
}
|
||||
(asset, _) => apply(app, asset),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Assets panel body (a dock tab).
|
||||
pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let tab_id = egui::Id::new("shelf_tab");
|
||||
let mut tab = ctx.data_mut(|d| *d.get_persisted_mut_or(tab_id, 0usize)).min(TABS.len() - 1);
|
||||
let mut tab = app.ui.shelf_tab.min(TABS.len() - 1);
|
||||
let searching = !app.ui.shelf_filter.is_empty();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(2.0, 2.0);
|
||||
@@ -92,7 +132,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
});
|
||||
ctx.data_mut(|d| d.insert_persisted(tab_id, tab));
|
||||
app.ui.shelf_tab = tab;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(TOKENS.text_dim));
|
||||
ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text("Search all assets").desired_width(f32::INFINITY));
|
||||
@@ -112,6 +152,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
library(app, ui, &filter);
|
||||
}
|
||||
Tab::Masks => smart_masks(app, ui, &ctx, &filter, title),
|
||||
Tab::Filters => filters(app, ui, &ctx, &filter, title),
|
||||
Tab::Alphas => alpha_library(app, ui, &ctx, &filter, title),
|
||||
Tab::Procedurals => procedurals(app, ui, &ctx, &filter, title),
|
||||
Tab::Environments => environments(app, ui, &filter, title),
|
||||
@@ -126,7 +167,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
fn drag_preview(ctx: &egui::Context) {
|
||||
let (Some(d), Some(pos)) = (egui::DragAndDrop::payload::<ShelfDrag>(ctx), ctx.input(|i| i.pointer.hover_pos())) else { return };
|
||||
let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("shelf_drag")));
|
||||
let galley = p.layout_no_wrap(d.label.to_string(), egui::FontId::proportional(11.0), TOKENS.text_strong);
|
||||
let galley = p.layout_no_wrap(d.label.clone(), egui::FontId::proportional(11.0), TOKENS.text_strong);
|
||||
let rect = egui::Rect::from_min_size(pos + vec2(14.0, 12.0), galley.size() + vec2(12.0, 6.0));
|
||||
p.rect_filled(rect, 3.0, TOKENS.row_selected);
|
||||
p.rect_stroke(rect, 3.0, Stroke::new(1.0, TOKENS.accent), egui::StrokeKind::Inside);
|
||||
@@ -182,9 +223,9 @@ fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter
|
||||
} else {
|
||||
"Add a fill layer with this material above the selected layer (or drag it into the layer stack)"
|
||||
};
|
||||
let drag = ShelfDrag { asset: Asset::Material(m.id), label: m.label };
|
||||
if tile(ui, tex.as_ref(), m.label, hint, Some(drag)).clicked() {
|
||||
apply(app, drag.asset);
|
||||
let asset = Asset::Material(m.id);
|
||||
if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() {
|
||||
apply(app, &asset);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -217,8 +258,15 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
|
||||
ui.label(RichText::new("Right-click a layer > Create smart material").size(10.0).color(TOKENS.text_dim));
|
||||
}
|
||||
for f in shown {
|
||||
if ui.selectable_label(false, format!("{} {}", ic::SPHERE, name(f))).on_hover_text(f.display().to_string()).clicked() {
|
||||
app.run("material.load", json!({"path": f.display().to_string()}));
|
||||
let (label, asset) = (name(f), Asset::Library(f.display().to_string()));
|
||||
let r = ui
|
||||
.add(egui::Button::selectable(false, format!("{} {label}", ic::SPHERE)).sense(Sense::click_and_drag()))
|
||||
.on_hover_text(format!("{}: add above the selected layer (or drag it into the layer stack or onto the viewport)", f.display()));
|
||||
if r.drag_started() {
|
||||
r.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label });
|
||||
}
|
||||
if r.clicked() {
|
||||
apply(app, &asset);
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
@@ -236,15 +284,42 @@ fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt
|
||||
tiles(ui, |ui| {
|
||||
for m in shown {
|
||||
let tex = app.thumbs.smart_mask(ctx, m.id);
|
||||
let drag = ShelfDrag { asset: Asset::SmartMask(m.id), label: m.label };
|
||||
let asset = Asset::SmartMask(m.id);
|
||||
let hint = "Replace the selected layer's mask with this smart mask (or drag it onto a layer)";
|
||||
if tile(ui, tex.as_ref(), m.label, hint, Some(drag)).clicked() {
|
||||
apply(app, drag.asset);
|
||||
if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() {
|
||||
apply(app, &asset);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The filter library, grouped: a click adds the filter to the selected layer's content (or its
|
||||
/// mask when the mask is selected), a drop onto a layer to that layer's content.
|
||||
fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
|
||||
let shown: Vec<_> = FILTERS.iter().filter(|f| matches(filter, &[f.label, f.group, f.id])).collect();
|
||||
if shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
title(ui, name);
|
||||
for group in categories(&shown, |f| f.group) {
|
||||
header(ui, group);
|
||||
tiles(ui, |ui| {
|
||||
for f in shown.iter().filter(|f| f.group == group) {
|
||||
let tex = app.thumbs.filter(ctx, f.id);
|
||||
let hint = if f.mask {
|
||||
"Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)"
|
||||
} else {
|
||||
"Add this finish to the selected layer's roughness and height (or drag it onto a layer)"
|
||||
};
|
||||
let asset = Asset::Filter(f.id);
|
||||
if tile(ui, tex.as_ref(), f.label, hint, Some(&asset)).clicked() {
|
||||
apply(app, &asset);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The built-in alpha library, grouped by category; the brush's alpha is outlined.
|
||||
fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
|
||||
let shown: Vec<&'static alphas::LibraryAlpha> = alphas::library().iter().filter(|a| matches(filter, &[&a.label, a.category, &a.id])).collect();
|
||||
@@ -259,13 +334,13 @@ fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, fi
|
||||
tiles(ui, |ui| {
|
||||
for &a in shown.iter().filter(|a| a.category == cat) {
|
||||
let tex = app.thumbs.alpha(ctx, a);
|
||||
let drag = ShelfDrag { asset: Asset::Alpha(&a.id), label: &a.label };
|
||||
let r = tile(ui, tex.as_ref(), &a.label, "Use as the brush alpha (or drag it onto the viewport or brush properties)", Some(drag));
|
||||
let asset = Asset::Alpha(&a.id);
|
||||
let r = tile(ui, tex.as_ref(), &a.label, "Use as the brush alpha (or drag it onto the viewport or brush properties)", Some(&asset));
|
||||
if current.as_deref() == Some(a.id.as_str()) {
|
||||
ui.painter().rect_stroke(r.rect, 3.0, Stroke::new(1.0, TOKENS.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
if r.clicked() {
|
||||
apply(app, drag.asset);
|
||||
apply(app, &asset);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -322,11 +397,16 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter:
|
||||
for name in names {
|
||||
let Some(img) = app.session.images.get(&name).cloned() else { continue };
|
||||
let tex = app.thumbs.image(ctx, &name, &img);
|
||||
let r = tile(ui, Some(&tex), &name, "Add a fill layer using this image", None);
|
||||
let asset = Asset::Texture(name.clone());
|
||||
let r = tile(ui, Some(&tex), &name, "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", Some(&asset));
|
||||
if r.clicked() {
|
||||
app.run("layer.add.image", json!({"name": name}));
|
||||
apply(app, &asset);
|
||||
}
|
||||
r.context_menu(|ui| {
|
||||
if ui.button("Add as decal (view center)").clicked() {
|
||||
app.run("layer.add.decal", json!({"image": name}));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Remove resource").clicked() {
|
||||
app.run("resource.remove", json!({"name": name}));
|
||||
ui.close();
|
||||
@@ -337,12 +417,14 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter:
|
||||
}
|
||||
|
||||
/// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with
|
||||
/// a `drag` payload can be dragged.
|
||||
fn tile(ui: &mut Ui, tex: Option<&egui::TextureHandle>, label: &str, hint: &str, drag: Option<ShelfDrag>) -> egui::Response {
|
||||
/// a `drag` asset can be dragged.
|
||||
fn tile(ui: &mut Ui, tex: Option<&egui::TextureHandle>, label: &str, hint: &str, drag: Option<&Asset>) -> egui::Response {
|
||||
let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() };
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(72.0, 86.0), sense);
|
||||
if let Some(d) = drag {
|
||||
resp.dnd_set_drag_payload(d);
|
||||
if let Some(asset) = drag
|
||||
&& resp.drag_started()
|
||||
{
|
||||
resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() });
|
||||
}
|
||||
let p = ui.painter();
|
||||
if resp.hovered() || resp.dragged() {
|
||||
|
||||
@@ -22,12 +22,14 @@ pub struct RenderUi {
|
||||
pub max_samples: u32,
|
||||
pub bounces: u32,
|
||||
pub denoise: bool,
|
||||
/// Path trace on the CPU even where the GPU tracer runs.
|
||||
pub cpu: bool,
|
||||
}
|
||||
|
||||
impl Default for RenderUi {
|
||||
fn default() -> Self {
|
||||
// The web traces on one thread: fewer bounces keep it interactive.
|
||||
RenderUi { max_samples: 256, bounces: if cfg!(target_arch = "wasm32") { 3 } else { 6 }, denoise: true }
|
||||
RenderUi { max_samples: 256, bounces: if cfg!(target_arch = "wasm32") { 3 } else { 6 }, denoise: true, cpu: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,6 +170,9 @@ pub struct UiState {
|
||||
/// Channel whose blending the layer rows show.
|
||||
pub layer_channel: Channel,
|
||||
pub shelf_filter: String,
|
||||
/// The asset shelf's open tab.
|
||||
#[serde(default)]
|
||||
pub shelf_tab: usize,
|
||||
pub props_tab: PropsTab,
|
||||
/// Layer being renamed and the edit buffer.
|
||||
pub rename: Option<(u64, String)>,
|
||||
@@ -218,6 +223,7 @@ impl Default for UiState {
|
||||
uv_pan: [0.0, 0.0],
|
||||
layer_channel: Channel::BaseColor,
|
||||
shelf_filter: String::new(),
|
||||
shelf_tab: 0,
|
||||
props_tab: PropsTab::Brush,
|
||||
rename: None,
|
||||
new_project: NewProject::default(),
|
||||
|
||||
@@ -17,7 +17,7 @@ const SPHERE_PX: usize = 72;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Thumbs {
|
||||
/// Shelf thumbnails by key (`mat:<id>`, `mask:<id>`, `proc:<kind>`, `alpha:<id>`).
|
||||
/// Shelf thumbnails by key (`mat:<id>`, `mask:<id>`, `filter:<id>`, `proc:<kind>`, `alpha:<id>`).
|
||||
shelf: HashMap<String, TextureHandle>,
|
||||
images: HashMap<String, TextureHandle>,
|
||||
/// (frame, thumbnails rendered in it).
|
||||
@@ -162,6 +162,11 @@ impl Thumbs {
|
||||
})
|
||||
}
|
||||
|
||||
/// Sphere thumbnail of library filter `id` applied to a sample material.
|
||||
pub fn filter(&mut self, ctx: &egui::Context, id: &str) -> Option<TextureHandle> {
|
||||
self.shelf(ctx, format!("filter:{id}"), || sphere_image(SPHERE_PX, &preview::filter(id, SPHERE_PX).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Grayscale swatch of procedural `k`.
|
||||
pub fn procedural(&mut self, ctx: &egui::Context, k: ProceduralKind) -> Option<TextureHandle> {
|
||||
use texturecraft_engine::compose::pattern::{Coords, procedural};
|
||||
|
||||
+108
-11
@@ -5,6 +5,7 @@ use std::sync::Mutex;
|
||||
|
||||
use egui::{Color32, PointerButton, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::camera_cmds::DEFAULT_CAMERA;
|
||||
use texturecraft_engine::core::{BakedMap, Channel};
|
||||
use texturecraft_engine::geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_engine::{Tool, ViewMode};
|
||||
@@ -18,6 +19,20 @@ use crate::theme::TOKENS;
|
||||
pub const VIEW_3D: u64 = 1;
|
||||
pub const VIEW_2D: u64 = 2;
|
||||
|
||||
/// While on, a click in the 3D view focuses the depth of field there (a transient UI mode kept in
|
||||
/// egui's memory).
|
||||
fn focus_pick_id() -> egui::Id {
|
||||
egui::Id::new("tc_focus_pick")
|
||||
}
|
||||
|
||||
pub fn focus_picking(ctx: &egui::Context) -> bool {
|
||||
ctx.data(|d| d.get_temp::<bool>(focus_pick_id())).unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn set_focus_picking(ctx: &egui::Context, on: bool) {
|
||||
ctx.data_mut(|d| d.insert_temp(focus_pick_id(), on));
|
||||
}
|
||||
|
||||
pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let aux = match app.session.view {
|
||||
_ if app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask),
|
||||
@@ -49,7 +64,10 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
// Keep drawing while the 3D view accumulates anti-aliasing samples (it stops on its own).
|
||||
let accumulating = layout != ViewLayout::Only2D
|
||||
&& app.render_state.as_ref().is_some_and(|rs| rs.renderer.read().callback_resources.get::<crate::gpu::GpuState>().is_some_and(|g| g.renderer.accumulating(VIEW_3D)));
|
||||
&& app
|
||||
.render_state
|
||||
.as_ref()
|
||||
.is_some_and(|rs| rs.renderer.read().callback_resources.get::<crate::gpu::GpuState>().is_some_and(|g| g.renderer.accumulating(VIEW_3D)));
|
||||
if app.session.stroke_active() || accumulating {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
@@ -71,7 +89,7 @@ fn shade(app: &TextureCraftApp) -> Shade {
|
||||
channel,
|
||||
wireframe: app.ui.uv_wireframe,
|
||||
wireframe_3d: app.ui.wireframe_3d,
|
||||
..Shade::from_display(&app.session.doc.project.display)
|
||||
..Shade::from_project(&app.session.doc.project)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,9 +119,21 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sy
|
||||
fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) {
|
||||
let header = Rect::from_min_size(rect.min + vec2(rect.width() * 0.5 - 150.0, 8.0), vec2(300.0, 22.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
egui::ComboBox::from_id_salt(format!("{id}_cam")).width(130.0).selected_text("Default camera").show_ui(&mut child, |ui| {
|
||||
if ui.selectable_label(true, "Default camera").clicked() {
|
||||
app.run("viewport.frame", json!({}));
|
||||
let current = texturecraft_engine::camera_cmds::current(&app.session);
|
||||
let names: Vec<String> = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect();
|
||||
let shown = current.and_then(|i| names.get(i)).map_or(DEFAULT_CAMERA, String::as_str);
|
||||
egui::ComboBox::from_id_salt(format!("{id}_cam")).width(130.0).selected_text(shown).show_ui(&mut child, |ui| {
|
||||
if ui.selectable_label(current.is_none(), DEFAULT_CAMERA).clicked() {
|
||||
app.run("camera.select", json!({}));
|
||||
}
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
if ui.selectable_label(current == Some(i), name).clicked() {
|
||||
app.run("camera.select", json!({"index": i}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.selectable_label(false, "Save view as camera").clicked() {
|
||||
app.run("camera.add", json!({}));
|
||||
}
|
||||
});
|
||||
let label = app.session.view.label();
|
||||
@@ -197,9 +227,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
}
|
||||
|
||||
// Stencil: S + left drag rotates, S + right drag scales, S + middle drag moves.
|
||||
if s_held
|
||||
&& let Some(st) = app.session.tool.stencil.as_mut()
|
||||
{
|
||||
if s_held && let Some(st) = app.session.tool.stencil.as_mut() {
|
||||
if resp.dragged_by(PointerButton::Primary) {
|
||||
st.rotation = (st.rotation + delta.x * 0.4).rem_euclid(360.0);
|
||||
} else if resp.dragged_by(PointerButton::Secondary) {
|
||||
@@ -219,8 +247,34 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let (q, vp) = (local(p), app.session.viewport);
|
||||
app.run("tool.cloneSource", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}));
|
||||
}
|
||||
// Depth of field focus pick: a click focuses there instead of painting.
|
||||
let focus_pick = focus_picking(ui.ctx());
|
||||
if focus_pick {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
if !alt
|
||||
&& resp.clicked_by(PointerButton::Primary)
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
let (q, vp) = (local(p), app.session.viewport);
|
||||
app.run("viewport.focusAt", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}));
|
||||
set_focus_picking(ui.ctx(), false);
|
||||
}
|
||||
}
|
||||
// Decal placement: a click moves the decal being placed there.
|
||||
let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting);
|
||||
if let Some(layer) = placing {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
if !alt
|
||||
&& resp.clicked_by(PointerButton::Primary)
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
let (q, vp) = (local(p), app.session.viewport);
|
||||
app.run("layer.decal.set", json!({"layer": layer.0, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}));
|
||||
app.placing_decal = None;
|
||||
}
|
||||
}
|
||||
// Painting.
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !s_held && !v_held;
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !s_held && !v_held && !focus_pick && placing.is_none();
|
||||
let path_tool = app.session.tool.tool == Tool::Path;
|
||||
let vp = app.session.viewport;
|
||||
let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p);
|
||||
@@ -279,7 +333,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
};
|
||||
add_callback(app, ui, rect, frame, sync);
|
||||
// Shelf drops: a material goes above the selection (as in Painter), an alpha on the brush.
|
||||
crate::shelf::drop_target(app, ui, &resp, true);
|
||||
crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d);
|
||||
|
||||
// Brush cursor.
|
||||
if app.ui.mode == crate::state::Mode::Painting
|
||||
@@ -308,6 +362,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
path_overlay(app, ui, rect, &resp, false, show);
|
||||
}
|
||||
stencil_overlay(app, ui, rect);
|
||||
decal_overlay(app, ui, rect);
|
||||
if app.session.quick_mask.editing {
|
||||
ui.painter_at(rect).text(
|
||||
rect.left_top() + vec2(12.0, 40.0),
|
||||
@@ -321,6 +376,48 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
axis_gizmo(ui, rect, app, false);
|
||||
}
|
||||
|
||||
/// The frame of the selected decal layer over the 3D view (a hint while placing it): outline,
|
||||
/// a tick on its top edge and its projection direction.
|
||||
fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) {
|
||||
use texturecraft_engine::core::{Fill, LayerKind, Projection};
|
||||
let p = &app.session.doc.project;
|
||||
let sel = app.session.selected_layer().and_then(|id| p.content_layer(id));
|
||||
let decal = match sel.map(|l| &l.kind) {
|
||||
Some(LayerKind::Fill(Fill { projection: Projection::Decal(d), .. })) => Some(*d),
|
||||
_ => None,
|
||||
};
|
||||
// Placing follows the selection: another layer selected stops it.
|
||||
if app.placing_decal.is_some() && app.placing_decal != sel.map(|l| l.id).filter(|_| decal.is_some()) {
|
||||
app.placing_decal = None;
|
||||
}
|
||||
let painter = ui.painter_at(rect);
|
||||
if app.placing_decal.is_some() {
|
||||
let hint = "Click the mesh to place the decal";
|
||||
painter.text(rect.left_top() + vec2(12.0, 40.0), egui::Align2::LEFT_TOP, hint, egui::FontId::proportional(12.0), TOKENS.accent);
|
||||
}
|
||||
let Some((d, corners)) = decal.and_then(|d| Some((d, texturecraft_engine::compose::pattern::decal_corners(&d)?))) else { return };
|
||||
let pts: Vec<Pos2> = corners.iter().filter_map(|c| project(app, rect, *c)).collect();
|
||||
let (Some(axes), true) = (texturecraft_engine::compose::pattern::decal_axes(&d), pts.len() == 4) else { return };
|
||||
let mut outline = pts.clone();
|
||||
outline.extend(pts.first().copied());
|
||||
for (w, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, Color32::from_white_alpha(220))] {
|
||||
painter.add(egui::Shape::dashed_line(&outline, Stroke::new(w, color), 6.0, 4.0));
|
||||
}
|
||||
// Top edge tick and the projection direction from the center.
|
||||
let (o, _, up, n) = axes;
|
||||
let top = (corners[0] + corners[1]) * 0.5;
|
||||
let reach = d.size[0].max(d.size[1]) * 0.25;
|
||||
for (a, b) in [(top, top + up * reach * 0.4), (o, o + n * reach)] {
|
||||
if let (Some(a), Some(b)) = (project(app, rect, a), project(app, rect, b)) {
|
||||
painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(140)));
|
||||
painter.line_segment([a, b], Stroke::new(1.4, TOKENS.accent));
|
||||
}
|
||||
}
|
||||
if let Some(c) = project(app, rect, o) {
|
||||
painter.circle(c, 3.5, TOKENS.accent, Stroke::new(1.0, Color32::from_black_alpha(180)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the projection stencil over the 3D view.
|
||||
fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) {
|
||||
if app.session.tool.tool != Tool::Projection {
|
||||
@@ -600,7 +697,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(),
|
||||
};
|
||||
add_callback(app, ui, rect, frame, sync);
|
||||
crate::shelf::drop_target(app, ui, &resp, true);
|
||||
crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View2d);
|
||||
// The UV tile outlines (numbered for UDIM sets) and the path being edited.
|
||||
let painter = ui.painter_at(rect);
|
||||
let set = app.session.doc.project.texture_sets.get(ts);
|
||||
|
||||
@@ -63,11 +63,28 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.add_space(6.0);
|
||||
ui.label(caption("Camera settings"));
|
||||
slider(ui, "Field of view (deg)", &mut d.fov, 5.0..=120.0, 0);
|
||||
let mut ortho = app.session.camera.ortho;
|
||||
if ui.checkbox(&mut ortho, "Orthographic").changed() {
|
||||
app.run("camera.set", json!({"ortho": ortho}));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Tone mapping");
|
||||
ui.selectable_value(&mut d.tone_mapping, ToneMapping::Linear, "Linear");
|
||||
ui.selectable_value(&mut d.tone_mapping, ToneMapping::AcesFilmic, "ACES filmic");
|
||||
});
|
||||
cameras(app, ui);
|
||||
ui.add_space(6.0);
|
||||
ui.label(caption("Depth of field"));
|
||||
ui.checkbox(&mut d.dof.enabled, "Depth of field (viewport and Rendering mode)");
|
||||
ui.add_enabled_ui(d.dof.enabled, |ui| {
|
||||
let far = (app.session.camera.distance * 4.0).max(d.dof.focus_distance);
|
||||
slider(ui, "Focus distance", &mut d.dof.focus_distance, 0.0..=far, 2).on_hover_text("Depth of the sharp plane along the view (0: the orbit center)");
|
||||
slider(ui, "Aperture", &mut d.dof.aperture, 0.0..=1.0, 3).on_hover_text("Lens size: how quickly things blur away from the focus distance");
|
||||
let picking = crate::viewport::focus_picking(ui.ctx());
|
||||
if ui.selectable_label(picking, format!("{} Pick focus in the viewport", ic::CROSSHAIR_SIMPLE)).clicked() {
|
||||
crate::viewport::set_focus_picking(ui.ctx(), !picking);
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(caption("Viewer settings"));
|
||||
slider(ui, "Ambient occlusion intensity", &mut d.ao_intensity, 0.0..=1.0, 2);
|
||||
@@ -75,7 +92,9 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.checkbox(&mut app.ui.uv_wireframe, "Show UV wireframe in the 2D view");
|
||||
ui.checkbox(&mut d.taa, "Temporal anti-aliasing (refines the 3D view while it is still)");
|
||||
if d != before {
|
||||
app.session.camera.fov = d.fov;
|
||||
if d.fov != before.fov {
|
||||
app.session.camera.fov = d.fov;
|
||||
}
|
||||
app.session.doc.project.display = d;
|
||||
}
|
||||
if import_hdr {
|
||||
@@ -83,6 +102,39 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera list: rename (edit the name), view or delete saved and imported cameras, save the
|
||||
/// current view.
|
||||
fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let current = texturecraft_engine::camera_cmds::current(&app.session);
|
||||
let names: Vec<String> = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
if icon_button(ui, ic::VIDEO_CAMERA, "View through this camera", current == Some(i), 20.0).clicked() {
|
||||
app.run("camera.select", json!({"index": i}));
|
||||
}
|
||||
// The name being typed lives in egui's memory until the field loses focus.
|
||||
let id = ui.id().with(("camera_name", i));
|
||||
let mut text = ui.data(|d| d.get_temp::<String>(id)).unwrap_or_else(|| name.clone());
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(ui.available_width() - 26.0));
|
||||
if r.changed() {
|
||||
ui.data_mut(|d| d.insert_temp(id, text.clone()));
|
||||
}
|
||||
if r.lost_focus() {
|
||||
ui.data_mut(|d| d.remove::<String>(id));
|
||||
if text.trim() != name && !text.trim().is_empty() {
|
||||
app.run("camera.rename", json!({"index": i, "to": text.trim()}));
|
||||
}
|
||||
}
|
||||
if icon_button(ui, ic::TRASH, "Delete this camera", false, 20.0).clicked() {
|
||||
app.run("camera.remove", json!({"index": i}));
|
||||
}
|
||||
});
|
||||
}
|
||||
if ui.button(format!("{} Save view as camera", ic::PLUS)).clicked() {
|
||||
app.run("camera.add", json!({}));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Shader Settings panel body (a dock tab).
|
||||
pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let mut d = app.session.doc.project.display.clone();
|
||||
@@ -98,7 +150,7 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
} else {
|
||||
"Base color, Metallic, Roughness and Specular level."
|
||||
};
|
||||
ui.label(RichText::new(format!("GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading. {channels} Optional channels add a clear coat (Coat weight, Coat roughness), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle) and subsurface scattering (Scattering weight).")).color(TOKENS.text_dim));
|
||||
ui.label(RichText::new(format!("GGX specular with height-correlated Smith visibility, Lambert diffuse, split-sum image-based lighting with spherical-harmonics irradiance and horizon fading. {channels} Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).")).color(TOKENS.text_dim));
|
||||
ui.add_space(6.0);
|
||||
ui.checkbox(&mut d.parallax, "Parallax occlusion (height channel)")
|
||||
.on_hover_text("Offsets the textures by the height channel, at the height to normal strength");
|
||||
@@ -112,6 +164,10 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
.on_hover_text("Color of the light that travels under the surface (each channel goes as far as its value)");
|
||||
slider(ui, "Scatter radius", &mut d.scatter_radius, 0.0..=1.0, 3)
|
||||
.on_hover_text("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)");
|
||||
ui.add_space(6.0);
|
||||
ui.label(caption("Transmission"));
|
||||
slider(ui, "Index of refraction", &mut d.ior, 1.0..=3.0, 2)
|
||||
.on_hover_text("How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42");
|
||||
if d != before {
|
||||
app.session.doc.project.display = d;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ a `path`) is refused, and so is any command given a `path` or `dir` (`resource.i
|
||||
| `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root |
|
||||
| `bake` | `{ts?, resolution?, maps?}` | Mesh maps for generators and smart materials |
|
||||
| `paint_stroke` | `{points, viewport?, color?, roughness?, metallic?, height?, size?, hardness?}` | Paint tool + brush material + `tool.stroke`; points in viewport pixels |
|
||||
| `viewport_render` | `{view?: "3d" \| "2d", width?, height?, yaw?, pitch?, samples?, bounces?}` | Headless: PNG image (≤ 2048 px a side); yaw/pitch in degrees for this render only; `samples` (1–4096) path traces the 3D view on the CPU instead (no GPU needed) |
|
||||
| `viewport_render` | `{view?: "3d" \| "2d", width?, height?, yaw?, pitch?, samples?, bounces?, cpu?}` | Headless: PNG image (≤ 2048 px a side); yaw/pitch in degrees for this render only; `samples` (1–4096) path traces the 3D view instead, on the GPU when it has compute shaders, else (or with `cpu: true`) on the CPU (no GPU needed) |
|
||||
| `viewport_screenshot` | `{view?}` | Bridge: the app's 3D or 2D view |
|
||||
| `ui_screenshot` | | Bridge: the whole window (downscaled to 2048 px) |
|
||||
| `ui_inspect` | | Bridge: UI state |
|
||||
|
||||
Reference in new issue
Block a user