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 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
leValdemar19
2026-10-31 13:30:07 +00:00
committed by GitHub
parent f0acea0992
commit 3385d1c570
11 changed files with 144 additions and 2 deletions
@@ -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"
}
}
+29
View File
@@ -20,6 +20,7 @@ struct U {
sel: vec4<f32>, // xyz a whole selected body's colour before lighting
product_lights_meta: vec4<f32>, // explicit preview flag and bounded count
product_lights: array<vec4<f32>,84>, // position/kind, radiance, axis/cone, attenuation
sky: vec4<f32>, // 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<f32> {
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<f32>) -> vec3<f32> {
return select(c / 12.92, pow((c + vec3<f32>(0.055)) / vec3<f32>(1.055), vec3<f32>(2.4)), c > vec3<f32>(0.04045));
}
fn srgb_encode(c: vec3<f32>) -> vec3<f32> {
let l = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
return select(l * 12.92, 1.055 * pow(l, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), l > vec3<f32>(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<f32>, n: vec3<f32>, diff: f32, fill: f32, visibility: f32) -> vec3<f32> {
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<f32>(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<f32>) -> vec4<f32> {
@@ -576,6 +602,9 @@ fn lit_color(i: TOut, visibility: f32, base: vec4<f32>) -> vec4<f32> {
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<f32>(min(sky_lit(base.rgb, n, diff, fill, visibility) + vec3<f32>(spec), vec3<f32>(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<f32>(min(base.rgb * k + vec3<f32>(spec), vec3<f32>(1.0)), base.a));
}
+1
View File
@@ -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],
+32 -2
View File
@@ -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<f32> = 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,
}
}
+1
View File
@@ -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],
+1
View File
@@ -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],
});
+28
View File
@@ -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.
+2
View File
@@ -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"));
+1
View File
@@ -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],
+1
View File
@@ -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],
+14
View File
@@ -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],