From 088aa4eb069783a4bed320883a6a3452f731d27c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 21 Nov 2026 22:00:14 +0100 Subject: [PATCH] feat(render): add IOR-based dielectric reflection Let Metallic/Roughness projects opt into dielectric F0 derived from the index of refraction. Share the Specular Level multiplier across the viewport, CPU and GPU path tracing, and the derived F0 texture export. Store the choice with projects and templates. Keep the legacy factor for existing projects and authored RGB F0 in Specular/Glossiness. --- crates/core/src/project.rs | 18 ++++++++++++++++++ crates/engine/src/template_cmds.rs | 7 ++++++- crates/engine/src/view_cmds.rs | 5 ++++- crates/formats/src/export/mod.rs | 6 ++++-- crates/render/src/gpu_trace.rs | 4 +++- crates/render/src/renderer.rs | 7 ++++++- crates/render/src/shaders/mesh.wgsl | 5 +++-- crates/render/src/shaders/trace.wgsl | 4 ++-- crates/render/src/trace.rs | 8 ++++++-- crates/ui-egui/src/shader_settings.rs | 13 ++++++++++--- docs/control-protocol.md | 2 ++ 11 files changed, 64 insertions(+), 15 deletions(-) diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index ce14606b..8b2c70f1 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -312,6 +312,8 @@ pub struct DisplaySettings { pub scatter_radius: f32, /// Index of refraction of transmissive surfaces (where the Transmission channel is painted). pub ior: f32, + /// Use IOR to determine dielectric reflectance at normal incidence in Metallic/Roughness. + pub ior_specular: bool, /// Depth of field of the viewport and the path tracer (thin lens). pub dof: DepthOfField, } @@ -367,11 +369,26 @@ pub const ENVIRONMENTS: [&str; 6] = ["Studio Soft", "Studio Contrast", "Overcast /// Prefix of [`DisplaySettings::environment`] naming an image resource. pub const ENV_RESOURCE_PREFIX: &str = "resource:"; +/// Original dielectric F0 multiplier for the Specular Level channel. +pub const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; + impl DisplaySettings { /// The image resource used as the environment, if any. pub fn environment_resource(&self) -> Option<&str> { self.environment.strip_prefix(ENV_RESOURCE_PREFIX) } + + /// Multiplier for Specular Level in the Metallic/Roughness model. + pub fn dielectric_f0_scale(&self) -> f32 { + if self.ior_specular && !self.spec_gloss && self.ior.is_finite() { + let ior = self.ior.clamp(1.0, 3.0); + let fresnel = (ior - 1.0) / (ior + 1.0); + // Specular Level 0.5 represents OpenPBR's default specular weight of 1. + 2.0 * fresnel * fresnel + } else { + LEGACY_DIELECTRIC_F0_SCALE + } + } } impl Default for DisplaySettings { @@ -402,6 +419,7 @@ impl Default for DisplaySettings { scatter_color: [1.0, 0.4, 0.25], scatter_radius: 0.1, ior: 1.5, + ior_specular: false, dof: DepthOfField::default(), } } diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index 27de192d..3c227b01 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -36,6 +36,7 @@ pub struct ProjectTemplate { pub spec_gloss: bool, pub parallax: bool, pub ior: f32, + pub ior_specular: bool, pub scatter_color: [f32; 3], pub scatter_radius: f32, } @@ -51,6 +52,7 @@ impl Default for ProjectTemplate { spec_gloss: d.spec_gloss, parallax: d.parallax, ior: d.ior, + ior_specular: d.ior_specular, scatter_color: d.scatter_color, scatter_radius: d.scatter_radius, } @@ -116,7 +118,7 @@ pub fn specs() -> Vec { "Project templates", [], None, - "{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss}]", + "{} → [{name, label, builtin, resolution, normalFormat, channels: [ids], specGloss, iorSpecular}]", always, list ), @@ -196,6 +198,7 @@ impl Session { p.normal_format = t.normal_format; let d = &mut p.display; (d.spec_gloss, d.parallax, d.ior, d.scatter_color, d.scatter_radius) = (t.spec_gloss, t.parallax, t.ior, t.scatter_color, t.scatter_radius); + d.ior_specular = t.ior_specular; for ts in 0..p.texture_sets.len() { if let Some(set) = p.texture_sets.get_mut(ts) { set.channels = t.channels.clone(); @@ -277,6 +280,7 @@ fn list(s: &mut Session, _: &Value) -> Result { "normalFormat": if t.normal_format == NormalFormat::DirectX { "directX" } else { "openGl" }, "channels": t.channels.iter().map(|(c, _)| c.id()).collect::>(), "specGloss": t.spec_gloss, + "iorSpecular": t.ior_specular, }) }; Ok(json!(builtin_templates().iter().map(|t| entry(t, true)).chain(s.templates.list.iter().map(|t| entry(t, false))).collect::>())) @@ -296,6 +300,7 @@ fn save(session: &mut Session, params: &Value) -> Result { spec_gloss: display.spec_gloss, parallax: display.parallax, ior: display.ior, + ior_specular: display.ior_specular, scatter_color: display.scatter_color, scatter_radius: display.scatter_radius, }; diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index e8161c8e..e1d01fd7 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Display settings", [], None, - "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, 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)}}", + "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, shadowMode? (intensive|average|lightweight: the shadow map resolution), shadowOpacity? (0..1: how dark the shadows are), alignment? (world|camera: what the environment turns with), soloUnlit? (single-channel views flat; off: lit), aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3), iorSpecular? (use IOR for dielectric reflectance at normal incidence in Metallic Roughness), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}", always, display ), @@ -297,6 +297,7 @@ fn display(s: &mut Session, p: &Value) -> Result { let scatter_color = color_param("display.set", p, "scatterColor")?; let d = &mut s.doc.project.display; + let (old_ior, old_ior_specular, old_spec_gloss) = (d.ior, d.ior_specular, d.spec_gloss); if let Some(e) = env { d.environment = e; } @@ -349,6 +350,7 @@ fn display(s: &mut Session, p: &Value) -> Result { ("postEffects", &mut d.post_effects), ("taa", &mut d.taa), ("specGloss", &mut d.spec_gloss), + ("iorSpecular", &mut d.ior_specular), ("parallax", &mut d.parallax), ("displacement", &mut d.displacement), ("soloUnlit", &mut d.solo_unlit), @@ -358,6 +360,7 @@ fn display(s: &mut Session, p: &Value) -> Result { } } + s.modified |= d.ior_specular != old_ior_specular || (d.ior_specular && (d.ior != old_ior || d.spec_gloss != old_spec_gloss)); // 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; diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index cdcb9c36..31b8b626 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -196,7 +196,7 @@ pub enum VirtualMap { Glossiness, /// Baked AO × AO channel (per the texture set's AO mixing). AoMixed, - /// Dielectric reflectance at normal incidence: 0.08 × specular level. + /// Dielectric reflectance at normal incidence: Specular Level scaled by the project's shader settings. F0, /// 1 − glossiness (specular/glossiness projects). Roughness, @@ -742,6 +742,7 @@ struct Sampler<'a> { /// Normal convention overriding every normal output. normal_override: Option, project_normal: NormalFormat, + dielectric_f0_scale: f32, } fn unpack(v: [f32; 3]) -> Vec3 { @@ -828,7 +829,7 @@ impl Sampler<'_> { VirtualMap::NormalOpenGl => self.normal(at, NormalFormat::OpenGl, cache), VirtualMap::NormalDirectX => self.normal(at, NormalFormat::DirectX, cache), VirtualMap::Glossiness => [1.0 - self.channel(Channel::Roughness, at)[0]; 3], - VirtualMap::F0 => [0.08 * self.channel(Channel::SpecularLevel, at)[0]; 3], + VirtualMap::F0 => [self.dielectric_f0_scale * self.channel(Channel::SpecularLevel, at)[0]; 3], VirtualMap::Roughness => [1.0 - self.channel(Channel::Glossiness, at)[0]; 3], VirtualMap::SheenTint => self.channel(Channel::SheenColor, at).map(|c| c * self.channel(Channel::SheenWeight, at)[0]), VirtualMap::HeightNormal => { @@ -900,6 +901,7 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result, ior: f32, + dielectric_f0_scale: f32, /// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole). lens: [f32; 2], } @@ -418,6 +419,7 @@ impl GpuTracer { env_camera: scene.env_camera, heights: scene.sets.iter().map(|s| s.height_strength).collect(), ior: scene.ior, + dielectric_f0_scale: scene.dielectric_f0_scale, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), }); Ok(()) @@ -609,7 +611,7 @@ impl GpuTracer { 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], + lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, sc.dielectric_f0_scale], }; let mut sets = [[0.0f32; 4]; 256]; for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() { diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 5e0561af..a1717936 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -25,6 +25,7 @@ use std::collections::HashMap; use bytemuck::{Pod, Zeroable}; use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_core::project::LEGACY_DIELECTRIC_F0_SCALE; use texturecraft_core::{Channel, DisplaySettings, EnvAlignment, Project, ToneMapping}; use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; @@ -206,6 +207,8 @@ pub struct Shade { pub scatter: [f32; 3], /// Index of refraction of the Transmission channel. pub ior: f32, + /// Multiplier for Specular Level when shading a dielectric in Metallic/Roughness. + pub dielectric_f0_scale: 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]>, @@ -258,6 +261,7 @@ impl Shade { taa: d.taa, scatter: scatter_wrap(d), ior: d.ior, + dielectric_f0_scale: d.dielectric_f0_scale(), dof: d.dof.enabled.then_some([d.dof.focus_distance, d.dof.aperture]), displacement: d.displacement, solo_lit: !d.solo_unlit, @@ -313,6 +317,7 @@ impl Default for Shade { taa: false, scatter: scatter_wrap(&DisplaySettings::default()), ior: 1.5, + dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE, dof: None, sss_blur: None, refraction: false, @@ -2124,7 +2129,7 @@ impl Renderer { 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], disp, - refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], + refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, s.dielectric_f0_scale], highlight: highlight_globals(s, data), highlight_shift: highlight_shift(frame.size), ..bake_globals(s.bake) diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 31fd19df..9dde8ff3 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -23,7 +23,7 @@ struct Globals { scatter: vec4, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1) fwd: vec4, // xyz camera view direction (unit), w - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - - refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - + refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w dielectric F0 scale highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - bake_high: vec4, // bake mode: rgb high poly color, a - @@ -529,7 +529,8 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let rough = clamp(orm.g, SPECULAR_ROUGHNESS_FLOOR, 1.0); let metal = orm.b; let nov = clamp(abs(dot(n, v)), GRAZING_COSINE_FLOOR, 1.0); - var f0 = mix(vec3(0.08 * orm.a), albedo, metal); + let dielectric_f0_scale = select(g.refr.w, 0.08, solo_lit); + var f0 = mix(vec3(dielectric_f0_scale * orm.a), albedo, metal); var diffuse_col = albedo * (1.0 - metal); if (g.material.x > 0.5 && !solo_lit) { // Specular color gives F0 (a solo-lit channel view keeps its neutral material); remove its energy from diffuse diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 5f6258e0..b4a4bba2 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -17,7 +17,7 @@ struct Params { env: vec4, // sin and cos of the environment rotation sigma: vec4, // subsurface extinction per color channel eye: vec4, // camera position - lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR + lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR, dielectric F0 scale // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength. sets: array, MAX_SETS>, }; @@ -332,7 +332,7 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { 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(0.08 * level), base, metallic); + f0 = mix(vec3(P.lens.w * level), base, metallic); } // The coat normal packs x and y around 128 so flat stays exact diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 034330b0..1cfaf68f 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -23,7 +23,7 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_compose::{Composite, ImageRes}; use texturecraft_core::Channel; -use texturecraft_core::project::{DisplaySettings, EnvAlignment, ToneMapping}; +use texturecraft_core::project::{DisplaySettings, EnvAlignment, LEGACY_DIELECTRIC_F0_SCALE, ToneMapping}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; @@ -63,6 +63,8 @@ pub struct TraceScene { pub(crate) radius: f32, /// Index of refraction of the Transmission channel. pub ior: f32, + /// Multiplier for Specular Level in the Metallic/Roughness model. + pub(crate) dielectric_f0_scale: 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]>, @@ -103,6 +105,7 @@ impl TraceScene { scatter_sigma: Vec3::ONE, radius, ior: 1.5, + dielectric_f0_scale: LEGACY_DIELECTRIC_F0_SCALE, lens: None, }; let d = DisplaySettings::default(); @@ -137,6 +140,7 @@ impl TraceScene { scene.spec_gloss = display.spec_gloss; scene.set_scatter(display.scatter_color, display.scatter_radius); scene.ior = display.ior; + scene.dielectric_f0_scale = display.dielectric_f0_scale(); scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]); scene @@ -606,7 +610,7 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 } 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), metallic) + (base * (1.0 - metallic), Vec3::splat(scene.dielectric_f0_scale * level).lerp(base, metallic), metallic) }; let coat_base = if n_geo.dot(-d) > 0.0 { n_geo } else { geo }; let coat_n = match set { diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index ba00a046..42018c2d 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -70,8 +70,9 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { header(ui); let mut display = app.session.doc.project.display.clone(); + let mut ior_specular = display.ior_specular; section_page::show(ui, "shader_settings", &SECTIONS, |ui, index| match index { - 0 => shader_parameters(ui, &mut display), + 0 => shader_parameters(ui, &mut display, &mut ior_specular), _ => displacement(ui, &mut display), }); @@ -80,6 +81,9 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.session.modified = true; app.session.revision = app.session.revision.wrapping_add(1); } + if ior_specular != app.session.doc.project.display.ior_specular { + app.run("display.set", serde_json::json!({"iorSpecular": ior_specular})); + } } /// Undo and Redo of the shader's settings, the shader button and the instance name @@ -139,7 +143,7 @@ pub fn matches_query(name: &str, query: &str) -> bool { } /// Base Surface, Specular, Transmission and Subsurface -fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { +fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings, ior_specular: &mut bool) { let tokens = Tokens::get(ui.ctx()); section(ui, "shader_base_surface", tr("Base Surface"), true, |ui| { shader_model(ui, display); @@ -148,8 +152,11 @@ fn shader_parameters(ui: &mut Ui, display: &mut DisplaySettings) { section(ui, "shader_specular", tr("Specular"), true, |ui| { unavailable::checkbox(ui, false, tr("Enable anisotropy")); slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( - "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + "Controls how strongly transmissive surfaces bend light. When the checkbox below is on, it also controls dielectric reflectance.", )); + ui.add_enabled(!display.spec_gloss, egui::Checkbox::new(ior_specular, tr("Use IOR for specular reflection"))) + .on_hover_text(tr("Uses the index of refraction for dielectric reflectance at normal incidence. Specular level adjusts its strength.")) + .on_disabled_hover_text(tr("Specular Glossiness uses the Specular color channel for reflectance.")); unavailable::checkbox(ui, false, tr("Enable specular color")); }); section(ui, "shader_transmission", tr("Transmission"), true, |ui| { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..fcb7b5e2 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -549,6 +549,8 @@ None is an undo step. `display.set` also takes `alignment` (`world` or `camera`: the environment, and the key light with it, turns with the camera about the vertical axis), `shadowMode` (`intensive`, `average` or `lightweight`, the default: the shadow map's resolution) and `shadowOpacity` (0 to 1, default 1: how dark the shadows are). +Set `iorSpecular` to true to use `ior` for dielectric reflectance at normal incidence in the +Metallic Roughness model. The setting defaults to false and is saved with the project and its templates. `viewport.view {mode: "image", image: }` shows a project image as it is, stretched over the UV square, on the mesh and in the 2D view (the view picker's "Other..."). `display.set {soloUnlit}`