From 3385d1c5702c7fb4688d862027e01ef42ff8d514 Mon Sep 17 00:00:00 2001 From: leValdemar19 Date: Sat, 31 Oct 2026 13:30:07 +0000 Subject: [PATCH] Viewport: dark parts keep their shape: linear-light shading and a sky fill (#7974) (#9028) * claim: #7974 * Viewport: dark parts keep their shape: linear-light shading and a sky fill (#7974) Preferences > Graphics "Keep the shape of dark parts" (off by default) shades the viewport in linear light: the key light and eye fill over a sky fill that grows as a face turns up, plus the 4% of that sky every dielectric reflects (a little more toward grazing), encoded to sRGB once. Near-black faces keep a gradient; light and mid-grey faces stay within a few levels of the sRGB shading. The world's up direction and the switch ride in a new `sky` vec4 at the end of the viewport uniform, and the frame key, so turning it on redraws. Off, the shader takes the old path unchanged. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../locales/pending/dark-parts-shading.json | 34 +++++++++++++++++++ assets/shaders/viewport.wgsl | 29 ++++++++++++++++ crates/gpu/src/capture.rs | 1 + crates/gpu/src/view.rs | 34 +++++++++++++++++-- crates/gpu/src/view/msaa_check.rs | 1 + crates/ui-egui/src/gpu.rs | 1 + crates/ui-egui/src/prefs.rs | 28 +++++++++++++++ crates/ui-egui/src/prefs/graphics.rs | 2 ++ crates/ui-egui/src/render_workspace.rs | 1 + crates/ui-egui/src/scale_tests.rs | 1 + crates/ui-egui/src/viewport.rs | 14 ++++++++ 11 files changed, 144 insertions(+), 2 deletions(-) create mode 100644 assets/locales/pending/dark-parts-shading.json diff --git a/assets/locales/pending/dark-parts-shading.json b/assets/locales/pending/dark-parts-shading.json new file mode 100644 index 000000000..629dd8b21 --- /dev/null +++ b/assets/locales/pending/dark-parts-shading.json @@ -0,0 +1,34 @@ +{ + "en": { + "prefs.dark_parts_shading": "Keep the shape of dark parts", + "prefs.dark_parts_shading_help": "Shade the view in linear light with a soft sky fill, so dark faces keep a gradient instead of turning black" + }, + "de": { + "prefs.dark_parts_shading": "Form dunkler Teile erhalten", + "prefs.dark_parts_shading_help": "Die Ansicht in linearem Licht mit sanftem Himmelslicht schattieren, damit dunkle Flächen einen Verlauf behalten statt schwarz zu werden" + }, + "ja": { + "prefs.dark_parts_shading": "暗い部品の形状を保つ", + "prefs.dark_parts_shading_help": "リニア光と柔らかいスカイライトでビューをシェーディングし、暗い面が黒くつぶれずにグラデーションを保つようにします" + }, + "ko": { + "prefs.dark_parts_shading": "어두운 부품의 형태 유지", + "prefs.dark_parts_shading_help": "선형 조명과 부드러운 하늘광으로 뷰를 음영 처리하여 어두운 면이 검게 뭉개지지 않고 그라데이션을 유지합니다" + }, + "zh": { + "prefs.dark_parts_shading": "保持深色零件的形状", + "prefs.dark_parts_shading_help": "以线性光照和柔和的天空补光着色视图,使深色面保留渐变而不变成一片黑色" + }, + "ar": { + "prefs.dark_parts_shading": "الحفاظ على شكل الأجزاء الداكنة", + "prefs.dark_parts_shading_help": "تظليل العرض بإضاءة خطية مع إضاءة سماء ناعمة، لتحتفظ الأوجه الداكنة بتدرج بدل أن تصبح سوداء" + }, + "he": { + "prefs.dark_parts_shading": "שמירה על צורת חלקים כהים", + "prefs.dark_parts_shading_help": "הצללת התצוגה באור ליניארי עם תאורת שמיים רכה, כך שפאות כהות שומרות על מעבר גוונים במקום להפוך לשחורות" + }, + "vi": { + "prefs.dark_parts_shading": "Giữ hình dạng của chi tiết tối", + "prefs.dark_parts_shading_help": "Tô bóng khung nhìn bằng ánh sáng tuyến tính với ánh sáng bầu trời dịu, để các mặt tối giữ được dải chuyển màu thay vì thành màu đen" + } +} diff --git a/assets/shaders/viewport.wgsl b/assets/shaders/viewport.wgsl index 2553c9746..140b23f6b 100644 --- a/assets/shaders/viewport.wgsl +++ b/assets/shaders/viewport.wgsl @@ -20,6 +20,7 @@ struct U { sel: vec4, // xyz a whole selected body's colour before lighting product_lights_meta: vec4, // explicit preview flag and bounded count product_lights: array,84>, // position/kind, radiance, axis/cone, attenuation + sky: vec4, // xyz = world up; w = 1: shade in linear light with a sky fill (#7974) }; fn reversed() -> bool { @@ -550,6 +551,31 @@ fn lit(i: TOut, visibility: f32) -> vec4 { return lit_color(i, visibility, i.c); } +/// sRGB to linear light, exact (the straight segment too, which `to_linear` leaves out). +fn srgb_decode(c: vec3) -> vec3 { + return select(c / 12.92, pow((c + vec3(0.055)) / vec3(1.055), vec3(2.4)), c > vec3(0.04045)); +} + +fn srgb_encode(c: vec3) -> vec3 { + let l = clamp(c, vec3(0.0), vec3(1.0)); + return select(l * 12.92, 1.055 * pow(l, vec3(1.0 / 2.4)) - vec3(0.055), l > vec3(0.0031308)); +} + +/// The studio light summed in linear light, encoded once (#7974): the key and the eye fill as in +/// [`lit_color`], over a sky fill that grows as the face turns up, and the 4% every dielectric +/// reflects of that sky (a little more toward grazing), so a near-black face keeps a gradient. The sky +/// and the fill are what ambient occlusion (`visibility`) takes away. sRGB out. +fn sky_lit(base: vec3, n: vec3, diff: f32, fill: f32, visibility: f32) -> vec3 { + let up = dot(n, normalize(u.sky.xyz)) * 0.5 + 0.5; + let sky = mix(0.18, 0.42, up); + // Schlick's rise toward grazing, tempered so mid-tones only gain a soft rim. + let fresnel = 0.04 + 0.2 * pow(1.0 - fill, 5.0); + let albedo = srgb_decode(base); + // Scaled so light and mid-grey faces land near where the sRGB shading puts them. + let light = albedo * (0.41 * diff + (0.66 * sky + 0.2 * fill) * visibility) + vec3(fresnel * sky * visibility); + return srgb_encode(light); +} + /// [`lit`] in a colour of its own: a whole highlighted body is lit in its colour lifted by the /// hover amount, or in the selection colour, from the model's own plan triangles. fn lit_color(i: TOut, visibility: f32, base: vec4) -> vec4 { @@ -576,6 +602,9 @@ fn lit_color(i: TOut, visibility: f32, base: vec4) -> vec4 { let fill = max(dot(n, v), 0.0); let h = normalize(key + v); let spec = pow(max(dot(n, h), 0.0), 40.0) * 0.25; + if u.sky.w > 0.5 { + return out_color(vec4(min(sky_lit(base.rgb, n, diff, fill, visibility) + vec3(spec), vec3(1.0)), base.a)); + } let k = 0.42 + 0.38 * diff + 0.25 * fill - (0.42 + 0.25 * fill) * (1.0 - visibility); return out_color(vec4(min(base.rgb * k + vec3(spec), vec3(1.0)), base.a)); } diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index 5dbae9b5c..c82e2bab3 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -405,6 +405,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces eye: [eye[0], eye[1], eye[2], if cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rs index e00534978..d11819683 100644 --- a/crates/gpu/src/view.rs +++ b/crates/gpu/src/view.rs @@ -153,8 +153,8 @@ fn octahedral6(n: [f32; 3]) -> u32 { } /// The shader's `U`: the view-projection matrix, 10 `vec4`s (the tenth carries the ambient /// occlusion radius), the 8 analysis colours, their flags, the depth direction and the two -/// whole-body highlight colours (`uniform_bytes`). -const UNIFORM_SIZE: u64 = 416 + 16 + 21 * 64; +/// whole-body highlight colours, the product lights, and the sky (`uniform_bytes`). +const UNIFORM_SIZE: u64 = 416 + 16 + 21 * 64 + 16; /// A body drawn from its display plan, evaluated on the GPU: the plan, and a palette index per /// face (the plan's face numbering; faces past the end take the last index). @@ -990,6 +990,9 @@ pub struct Frame { pub hover_tint: [f32; 3], /// Whole-body selection highlight: a selected body's colour before lighting (sRGB 0..1). pub selection_tint: [f32; 3], + /// The world's up direction and 1 to shade in linear light with a sky fill that follows it + /// (#7974); 0 shades as before. + pub sky: [f32; 4], } /// Heights of the model seen from a direction (an orthographic depth map): a point is reachable @@ -3309,6 +3312,7 @@ fn frame_key(cb: &Frame) -> u64 { // picture cached under the previous theme's colours is not shown (#5802). cb.hover_tint.map(f32::to_bits).hash(&mut h); cb.selection_tint.map(f32::to_bits).hash(&mut h); + cb.sky.map(f32::to_bits).hash(&mut h); cb.outline.hash(&mut h); cb.ao_radius.to_bits().hash(&mut h); cb.ao_samples.hash(&mut h); @@ -4169,6 +4173,7 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) - let light = cb.product_lights.as_ref().and_then(|lights| lights.get(index)).copied().unwrap_or([0.0; 16]); v.extend(light.map(|value| if value.is_finite() { value } else { 0.0 })); } + v.extend(cb.sky.map(|value| if value.is_finite() { value } else { 0.0 })); v.iter().flat_map(|x| x.to_le_bytes()).collect() } @@ -4364,6 +4369,28 @@ mod tests { assert_eq!(samples_sent(1000), 32.0, "at most the shader's 32"); } + /// The sky (#7974) is the uniform's last `vec4`: the world's up direction and the switch, with + /// anything not finite sent as zero (shaded as before). + #[test] + fn the_sky_rides_at_the_end_of_the_uniform() { + let last = |sky: [f32; 4]| { + let mut f = cached_frame(); + f.sky = sky; + let bytes = super::uniform_bytes(&f, 64.0, 64.0, false, false); + assert_eq!(bytes.len() as u64, super::UNIFORM_SIZE); + let v: Vec = bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + v[v.len() - 4..].to_vec() + }; + assert_eq!(last([0.0, 0.0, 1.0, 1.0]), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(last([0.0; 4]), [0.0; 4]); + assert_eq!(last([f32::NAN, 1.0, f32::INFINITY, 1.0]), [0.0, 1.0, 0.0, 1.0]); + // Turning it on draws the frame again. + let mut f = cached_frame(); + let off = super::frame_key(&f); + f.sky = [0.0, 0.0, 1.0, 1.0]; + assert_ne!(super::frame_key(&f), off); + } + #[test] fn render_lights_preview_shader_uniform_and_frame_cache_include_light_state() { let source = format!("{}\n{}", super::SHADER, crate::pbr::SOURCE); @@ -4415,6 +4442,7 @@ mod tests { eye: [0.0; 4], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, } } @@ -4800,6 +4828,7 @@ mod glass_tests { eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], @@ -4977,6 +5006,7 @@ mod glass_tests { eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa, } } diff --git a/crates/gpu/src/view/msaa_check.rs b/crates/gpu/src/view/msaa_check.rs index a70e7ab59..cc26caea4 100644 --- a/crates/gpu/src/view/msaa_check.rs +++ b/crates/gpu/src/view/msaa_check.rs @@ -121,6 +121,7 @@ impl Renderer { eye: [0.0, 0.0, 100.0, 0.0], ao_radius: 0.0, ao_samples: crate::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3], diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 8a1953938..d9cd92072 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -476,6 +476,7 @@ fn offscreen( ao_radius, ao_samples, ssaa, + sky: [0.0; 4], hover_tint: [0.0; 3], selection_tint: [0.0; 3], }); diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index b16a12514..f4f74443c 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -976,6 +976,9 @@ preference_settings! { graphics_adapter: String = String::new(), PAGE_GRAPHICS; /// Soft contact shading in the GPU viewport; optional and applied immediately. ambient_occlusion: bool = false, PAGE_GRAPHICS; + /// Shade the viewport in linear light with a sky fill, so dark parts keep their shape + /// (#7974). Off by default: the viewport shades as it always has. + dark_parts_shading: bool = false, PAGE_GRAPHICS => check_id("prefs.dark_parts_shading"); /// Optional schematic markings on threaded cylindrical walls; off for new and older preferences. cosmetic_threads: bool = false, PAGE_GRAPHICS; /// The grid turns to the upright origin plane facing a side view (#1470). Off by default: the @@ -8676,6 +8679,31 @@ mod ambient_occlusion_tests { assert_eq!(h.app.session.doc.to_json(), design); assert!(h.app.session.undo.is_empty()); } + + /// #7974: shading dark parts in linear light with a sky fill is off for older and new + /// preferences, turned on from the Graphics page, kept, and sent to the shader with the world's + /// up direction; Restore Defaults turns it off again. + #[test] + fn dark_parts_shading_is_optional_persistent_and_follows_the_up_axis() { + use solidcraft_engine::render::UpAxis; + let old: Prefs = serde_json::from_value(json!({"msaa": 4})).unwrap(); + assert!(!old.dark_parts_shading && !Prefs::default().dark_parts_shading); + assert_eq!(crate::viewport::sky_uniform(false, UpAxis::Z), [0.0; 4], "off: shaded as before"); + assert_eq!(crate::viewport::sky_uniform(true, UpAxis::Z), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(crate::viewport::sky_uniform(true, UpAxis::Y), [0.0, 1.0, 0.0, 1.0]); + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"open":"Graphics"})); + super::reveal_preference(&mut h, "prefs:dark_parts_shading"); + let checkbox = crate::scenario::handle_at("prefs:dark_parts_shading").unwrap(); + h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y})); + assert!(h.app.preferences.dark_parts_shading); + h.call("ui.prefs", json!({"button":"apply"})); + let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + restored.load_prefs(&h.app.prefs()); + assert!(restored.preferences.dark_parts_shading); + h.call("ui.prefs", json!({"button":"defaults"})); + assert!(!h.app.preferences.dark_parts_shading); + } } /// Manual edits are preserved and shown as Custom rather than claiming to match a preset. diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs index b2da292b1..4ad69d0e6 100644 --- a/crates/ui-egui/src/prefs/graphics.rs +++ b/crates/ui-egui/src/prefs/graphics.rs @@ -156,6 +156,8 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } }); ui_kit::text(ui, app.tr("prefs.contact_shading_note"), ui_kit::Text::Hint("ao")); + let response = setting::dark_parts_shading(app, ui).on_hover_text(app.tr("prefs.dark_parts_shading_help")); + crate::scenario::publish_handle("prefs:dark_parts_shading", response.rect.center()); }); ui_kit::settings_section(ui, "viewport", app.tr("prefs.viewport"), |ui| { let analysis_policy = setting::single_surface_analysis(app, ui).on_hover_text(app.tr("prefs.single_surface_analysis_help")); diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 509a8cc2e..c6ffcbeb7 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -2115,6 +2115,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // Product rendering has its own lighting; AO is a Design viewport setting. ao_radius: 0.0, ao_samples: solidcraft_gpu::view::AO_SAMPLES, + sky: [0.0; 4], eye: [eye.x as f32, eye.y as f32, eye.z as f32, if camera.fov > 0.0 { 1.0 } else { 0.0 }], ssaa: if width < full.0 { width as f32 / full.0 as f32 } else { 1.0 }, hover_tint: [f32::from(Tokens::get().hover_face_lift) / 255.0; 3], diff --git a/crates/ui-egui/src/scale_tests.rs b/crates/ui-egui/src/scale_tests.rs index 94e24aa65..703da2caf 100644 --- a/crates/ui-egui/src/scale_tests.rs +++ b/crates/ui-egui/src/scale_tests.rs @@ -291,6 +291,7 @@ pub(crate) fn view_frame( eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, ao_samples: solidcraft_gpu::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [f32::from(t.hover_face_lift) / 255.0; 3], selection_tint: [0.4, 0.6, 0.9], diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index b3ce67747..c85dbc5f0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -673,6 +673,18 @@ fn supersampling(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; /// Ambient occlusion samples per pixel this frame (#7165): the full count once the view has held /// still for a moment, fewer while it moves, so orbiting with AO on stays quick. +/// The shader's sky (#7974): the world's up direction, and 1 to shade in linear light with a sky +/// fill (Preferences › Graphics), else zero. +pub(crate) fn sky_uniform(on: bool, up: solidcraft_engine::render::UpAxis) -> [f32; 4] { + if !on { + return [0.0; 4]; + } + match up { + solidcraft_engine::render::UpAxis::Z => [0.0, 0.0, 1.0, 1.0], + solidcraft_engine::render::UpAxis::Y => [0.0, 1.0, 0.0, 1.0], + } +} + fn ao_samples(app: &mut SolveApp, ctx: &egui::Context, view_proj: [[f32; 4]; 4], size_px: [f32; 2]) -> u32 { // Without AO (off, or wireframe) the count is unused: no repaint is asked for it. if !app.preferences.ambient_occlusion || app.ui.visual_style == 2 || view_settled(app, ctx, view_proj, size_px) { @@ -4322,6 +4334,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let c = t.body_selected; [f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0] }, + sky: sky_uniform(app.preferences.dark_parts_shading, proj.cam.up), }); painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb)); // The graphics card had no memory for the view's frame (#7296): say once why it looks @@ -7963,6 +7976,7 @@ mod tests { eye: [e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }], ao_radius: 0.0, ao_samples: solidcraft_gpu::view::AO_SAMPLES, + sky: [0.0; 4], ssaa: 1.0, hover_tint: [0.0; 3], selection_tint: [0.0; 3],