Add optional ambient occlusion and graphics quality presets (#1135)

Thanks @CypherNaught-0x.
This commit is contained in:
CypherNaugh_0x authored and GitHub committed 2026-10-18 21:29:03 -04:00
1 parent 6b1fc16d47
commit 8e762fee57
24 files changed
+735 -55

No files matched your search

+14
View File
@@ -359,6 +359,20 @@ In order of how much they'd help users:
3. **Drawings, CAM and mesh tools.** These are out of scope for now (see
[ROADMAP.md](ROADMAP.md)), but anyone who wants to own one is welcome.
## Updating the generated feature list
After adding or renaming commands, run `cargo xtask features`. The registry is the
source of truth for `docs/features.md`; do not hand-edit the generated rows.
The generator sorts commands by ID and omits global and per-section counters,
so additions to unrelated areas no longer rewrite shared summary lines.
If two branches still conflict in this file (for example, adjacent additions in
the same area), first resolve the command registry and source conflicts, then run
`cargo xtask features` again and stage the regenerated file. Do not use Git's
`union` merge driver: it can silently retain stale or duplicate command rows.
The generator tests cover stable ordering and additions that leave existing lines
unchanged. The initial switch to sorted rows is a one-time larger diff.
## Licence
By contributing you agree that your contribution is licensed as MIT OR Apache-2.0, like the rest
+4
View File
@@ -14,6 +14,10 @@ features → parametric timeline) as an open, pure-Rust, agent-drivable applicat
| Gates | `cargo xtask ci`: fmt, clippy -D warnings, tests, asset attribution, layering, wasm32 build — green |
| Time to a useful alpha (M0–M6) | ≈ **82 agent hours** remain (sum of the M1–M6 estimates below) |
Optional GPU viewport ambient occlusion is available in View settings and Graphics preferences,
with persistent settings, Performance/Quality graphics presets (Quality combines AO, Fine tessellation and adaptive 2× supersampling; manual combinations show Custom), and the
`view.ambient_occlusion` and `view.graphics_preset` commands. See [display settings](docs/ambient-occlusion.md).
## Scope (owner decision, 2026-10-07)
The issue batch adds preservation of blind pockets in through cuts, associative projected
+9
View File
@@ -425,8 +425,10 @@
"cmd.timeline_roll_to": "Verlaufsmarkierung verschieben",
"cmd.timeline_rollback": "Zeitleistenmarkierung verschieben",
"cmd.timeline_suppress": "Merkmal unterdrücken",
"cmd.view_ambient_occlusion": "Umgebungsverdeckung",
"cmd.view_apply": "Benannte Ansicht wiederherstellen",
"cmd.view_delete": "Benannte Ansicht löschen",
"cmd.view_graphics_preset": "Grafikprofil",
"cmd.view_list": "Benannte Ansichten auflisten",
"cmd.view_navigate": "Ansicht navigieren",
"cmd.view_rename": "Benannte Ansicht umbenennen",
@@ -756,6 +758,8 @@
"ui.ai_toolbar_button_note": "Die KI-Schaltfläche am rechten Ende der Werkzeugleiste. Strg+Umschalt+A und das Ansicht-Menü öffnen das Panel weiterhin.",
"ui.ai_undo_tip": "Alles, was der Agent für diese Nachricht geändert hat, in einem Schritt rückgängig machen",
"ui.all": "Alle",
"ui.ambient_occlusion": "Umgebungsverdeckung",
"ui.ambient_occlusion_help": "Sanfte Schattierung an Kontaktstellen und in Vertiefungen undurchsichtiger Flächen. Erfordert die GPU-Ansicht.",
"ui.analysis": "Analyse",
"ui.angle": "Winkel",
"ui.angle_decimals": "Winkel-Dezimalstellen",
@@ -910,6 +914,11 @@
"ui.fully_constrained": "Vollständig bestimmt",
"ui.general": "Allgemein",
"ui.graphics": "Grafik",
"ui.graphics_custom": "Benutzerdefiniert",
"ui.graphics_performance": "Leistung",
"ui.graphics_preset": "Grafikprofil",
"ui.graphics_preset_help": "Qualität: Umgebungsverdeckung, feine Anzeigequalität und adaptives 2× Supersampling. Leistung: keine Umgebungsverdeckung, normale Anzeigequalität und kein Supersampling. Manuelle Änderungen: Benutzerdefiniert. MSAA bleibt unverändert.",
"ui.graphics_quality": "Qualität",
"ui.groupSelected": "Auswahl gruppieren",
"ui.heading_assemble": "ZUSAMMENBAU",
"ui.heading_box": "BLOCK",
+9
View File
@@ -632,8 +632,10 @@
"cmd.timeline_roll_to": "Roll History Marker",
"cmd.timeline_rollback": "Move Timeline Marker",
"cmd.timeline_suppress": "Suppress Feature",
"cmd.view_ambient_occlusion": "Ambient Occlusion",
"cmd.view_apply": "Restore Named View",
"cmd.view_delete": "Delete Named View",
"cmd.view_graphics_preset": "Graphics Preset",
"cmd.view_list": "List Named Views",
"cmd.view_navigate": "Navigate View",
"cmd.view_rename": "Rename Named View",
@@ -1036,6 +1038,8 @@
"ui.ai_toolbar_button_note": "The AI button at the right end of the toolbar. Ctrl+Shift+A and the View menu still open the panel.",
"ui.ai_undo_tip": "Undo everything the agent changed for this message, as one step",
"ui.all": "All",
"ui.ambient_occlusion": "Ambient occlusion",
"ui.ambient_occlusion_help": "Soft shading where opaque surfaces meet. Requires the GPU viewport.",
"ui.analysis": "Analysis",
"ui.angle": "Angle",
"ui.angle_decimals": "Angle decimals",
@@ -1196,6 +1200,11 @@
"ui.fully_constrained": "Fully constrained",
"ui.general": "General",
"ui.graphics": "Graphics",
"ui.graphics_custom": "Custom",
"ui.graphics_performance": "Performance",
"ui.graphics_preset": "Graphics Preset",
"ui.graphics_preset_help": "Quality: ambient occlusion, Fine display quality and adaptive 2× supersampling. Performance: no ambient occlusion, Normal display quality and supersampling off. Manual changes show Custom. MSAA stays unchanged.",
"ui.graphics_quality": "Quality",
"ui.grid_follows_view": "Grid follows the view",
"ui.grid_follows_view_hint": "Side views show the grid on the upright plane facing them instead of the ground",
"ui.ground_shadow": "Ground shadow",
+9
View File
@@ -628,8 +628,10 @@
"cmd.timeline_roll_to": "Déplacer le marqueur d'historique",
"cmd.timeline_rollback": "Déplacer le marqueur de chronologie",
"cmd.timeline_suppress": "Désactiver la fonction",
"cmd.view_ambient_occlusion": "Occlusion ambiante",
"cmd.view_apply": "Restaurer la vue nommée",
"cmd.view_delete": "Supprimer la vue nommée",
"cmd.view_graphics_preset": "Préréglage graphique",
"cmd.view_list": "Lister les vues nommées",
"cmd.view_navigate": "Naviguer dans la vue",
"cmd.view_rename": "Renommer la vue nommée",
@@ -995,6 +997,8 @@
"ui.ai_toolbar_button_note": "Le bouton IA à l'extrémité droite de la barre d'outils. Ctrl+Shift+A et le menu Vue ouvrent toujours le panneau.",
"ui.ai_undo_tip": "Annuler tout ce que l'agent a modifié pour ce message, en une seule étape",
"ui.all": "Tout",
"ui.ambient_occlusion": "Occlusion ambiante",
"ui.ambient_occlusion_help": "Ombrage doux aux jonctions des surfaces opaques. Nécessite la vue GPU.",
"ui.analysis": "Analyse",
"ui.angle": "Angle",
"ui.angle_decimals": "Décimales des angles",
@@ -1155,6 +1159,11 @@
"ui.fully_constrained": "Entièrement contrainte",
"ui.general": "Général",
"ui.graphics": "Graphisme",
"ui.graphics_custom": "Personnalisé",
"ui.graphics_performance": "Performances",
"ui.graphics_preset": "Préréglage graphique",
"ui.graphics_preset_help": "Qualité : occlusion ambiante, tessellation fine et suréchantillonnage adaptatif 2×. Performances : sans occlusion ambiante, tessellation normale et sans suréchantillonnage. Les réglages manuels affichent Personnalisé. MSAA reste inchangé.",
"ui.graphics_quality": "Qualité",
"ui.grid_follows_view": "La grille suit la vue",
"ui.grid_follows_view_hint": "Dans les vues de côté, la grille s'affiche sur le plan vertical qui leur fait face plutôt que sur le sol",
"ui.ground_shadow": "Ombre au sol",
+9
View File
@@ -632,8 +632,10 @@
"cmd.timeline_roll_to": "履歴マーカーを移動",
"cmd.timeline_rollback": "タイムライン マーカーを移動",
"cmd.timeline_suppress": "フィーチャーを抑制",
"cmd.view_ambient_occlusion": "アンビエントオクルージョン",
"cmd.view_apply": "名前付きビューを復元",
"cmd.view_delete": "名前付きビューを削除",
"cmd.view_graphics_preset": "グラフィックスプリセット",
"cmd.view_list": "名前付きビューを一覧表示",
"cmd.view_navigate": "ビューナビゲーション",
"cmd.view_rename": "名前付きビューの名前を変更",
@@ -1036,6 +1038,8 @@
"ui.ai_toolbar_button_note": "ツールバー右端の AI ボタン。Ctrl+Shift+A と表示メニューからも引き続きパネルを開けます。",
"ui.ai_undo_tip": "このメッセージでエージェントが行った変更を、1回でまとめて元に戻します",
"ui.all": "すべて",
"ui.ambient_occlusion": "アンビエントオクルージョン",
"ui.ambient_occlusion_help": "不透明な面が接する部分に柔らかい陰影を加えます。GPUビューポートが必要です。",
"ui.analysis": "解析",
"ui.angle": "角度",
"ui.angle_decimals": "角度の小数点以下の桁数",
@@ -1196,6 +1200,11 @@
"ui.fully_constrained": "完全拘束",
"ui.general": "一般",
"ui.graphics": "グラフィックス",
"ui.graphics_custom": "カスタム",
"ui.graphics_performance": "パフォーマンス",
"ui.graphics_preset": "グラフィックスプリセット",
"ui.graphics_preset_help": "品質:アンビエントオクルージョン、細かい表示品質、適応型2×スーパーサンプリング。パフォーマンス:AOなし、標準の表示品質、スーパーサンプリングなし。手動変更はカスタムと表示されます。MSAAは変更されません。",
"ui.graphics_quality": "品質",
"ui.grid_follows_view": "グリッドをビューに追従させる",
"ui.grid_follows_view_hint": "側面ビューでは、グリッドを地面ではなく、そのビューに向いた垂直平面に表示します",
"ui.ground_shadow": "地面の影",
+9
View File
@@ -425,8 +425,10 @@
"cmd.timeline_roll_to": "이력 마커 이동",
"cmd.timeline_rollback": "타임라인 마커 이동",
"cmd.timeline_suppress": "특성 비활성화",
"cmd.view_ambient_occlusion": "앰비언트 오클루전",
"cmd.view_apply": "이름 있는 보기 복원",
"cmd.view_delete": "이름 있는 보기 삭제",
"cmd.view_graphics_preset": "그래픽 프리셋",
"cmd.view_list": "이름 있는 보기 목록",
"cmd.view_navigate": "보기 탐색",
"cmd.view_rename": "이름 있는 보기 이름 변경",
@@ -756,6 +758,8 @@
"ui.ai_toolbar_button_note": "도구 모음 오른쪽 끝의 AI 버튼. Ctrl+Shift+A와 보기 메뉴로도 패널을 열 수 있습니다.",
"ui.ai_undo_tip": "이 메시지에서 에이전트가 바꾼 모든 것을 한 번에 실행 취소",
"ui.all": "모두",
"ui.ambient_occlusion": "앰비언트 오클루전",
"ui.ambient_occlusion_help": "불투명한 표면이 만나는 곳에 부드러운 음영을 추가합니다. GPU 뷰포트가 필요합니다.",
"ui.analysis": "분석",
"ui.angle": "각도",
"ui.angle_decimals": "각도 소수점 자릿수",
@@ -910,6 +914,11 @@
"ui.fully_constrained": "완전 구속",
"ui.general": "일반",
"ui.graphics": "그래픽",
"ui.graphics_custom": "사용자 지정",
"ui.graphics_performance": "성능",
"ui.graphics_preset": "그래픽 프리셋",
"ui.graphics_preset_help": "품질: 앰비언트 오클루전, 세밀한 표시 품질, 적응형 2× 슈퍼샘플링. 성능: 앰비언트 오클루전 끄기, 보통 표시 품질, 슈퍼샘플링 끄기. 수동 변경 시 사용자 지정으로 표시됩니다. MSAA는 유지됩니다.",
"ui.graphics_quality": "품질",
"ui.groupSelected": "선택 항목 그룹화",
"ui.heading_assemble": "조립",
"ui.heading_box": "박스",
+9
View File
@@ -568,8 +568,10 @@
"cmd.timeline_roll_to": "Переместить маркер истории",
"cmd.timeline_rollback": "Сдвинуть маркер шкалы",
"cmd.timeline_suppress": "Подавить операцию",
"cmd.view_ambient_occlusion": "Окружающее затенение",
"cmd.view_apply": "Вернуть именованный вид",
"cmd.view_delete": "Удалить именованный вид",
"cmd.view_graphics_preset": "Графический профиль",
"cmd.view_list": "Список именованных видов",
"cmd.view_navigate": "Навигация вида",
"cmd.view_rename": "Переименовать именованный вид",
@@ -750,6 +752,8 @@
"ui.agent_cursor": "Курсор агента",
"ui.agent_cursor_speed": "Скорость курсора агента",
"ui.all": "Все",
"ui.ambient_occlusion": "Окружающее затенение",
"ui.ambient_occlusion_help": "Мягкое затенение в местах соприкосновения непрозрачных поверхностей. Требуется видовой экран GPU.",
"ui.analysis": "Анализ",
"ui.angle": "Угол",
"ui.angle_decimals": "Знаков после запятой (углы)",
@@ -899,6 +903,11 @@
"ui.fully_constrained": "Полностью определён",
"ui.general": "Общие",
"ui.graphics": "Графика",
"ui.graphics_custom": "Настраиваемый",
"ui.graphics_performance": "Производительность",
"ui.graphics_preset": "Графический профиль",
"ui.graphics_preset_help": "Качество: окружающее затенение, детальная тесселяция и адаптивный суперсэмплинг 2×. Производительность: без затенения, обычная тесселяция и без суперсэмплинга. Ручные изменения отображаются как настраиваемые. MSAA не меняется.",
"ui.graphics_quality": "Качество",
"ui.ground_shadow": "Тень на земле",
"ui.groupSelected": "Группировать выбранное",
"ui.heading_add_ins": "НАДСТРОЙКИ",
+9
View File
@@ -632,8 +632,10 @@
"cmd.timeline_roll_to": "滚动历史标记",
"cmd.timeline_rollback": "移动时间线标记",
"cmd.timeline_suppress": "抑制特征",
"cmd.view_ambient_occlusion": "环境光遮蔽",
"cmd.view_apply": "还原命名视图",
"cmd.view_delete": "删除命名视图",
"cmd.view_graphics_preset": "图形预设",
"cmd.view_list": "列出命名视图",
"cmd.view_navigate": "导航视图",
"cmd.view_rename": "重命名命名视图",
@@ -1036,6 +1038,8 @@
"ui.ai_toolbar_button_note": "工具栏右端的 AI 按钮。Ctrl+Shift+A 和视图菜单仍可打开面板。",
"ui.ai_undo_tip": "将智能体为此消息所做的全部更改一步撤销",
"ui.all": "全部",
"ui.ambient_occlusion": "环境光遮蔽",
"ui.ambient_occlusion_help": "在不透明表面相接处添加柔和阴影。需要 GPU 视口。",
"ui.analysis": "分析",
"ui.angle": "角度",
"ui.angle_decimals": "角度小数位",
@@ -1196,6 +1200,11 @@
"ui.fully_constrained": "完全约束",
"ui.general": "常规",
"ui.graphics": "图形",
"ui.graphics_custom": "自定义",
"ui.graphics_performance": "性能",
"ui.graphics_preset": "图形预设",
"ui.graphics_preset_help": "质量:环境光遮蔽、精细显示质量和自适应2×超采样。性能:关闭环境光遮蔽、普通显示质量和关闭超采样。手动修改显示为自定义。MSAA保持不变。",
"ui.graphics_quality": "质量",
"ui.grid_follows_view": "网格跟随视图",
"ui.grid_follows_view_hint": "在侧视图中,将网格显示在朝向该视图的竖直平面上,而不是地面上",
"ui.ground_shadow": "地面阴影",
+61 -2
View File
@@ -10,6 +10,7 @@ struct U {
acc_u: vec4<f32>, // accessibility map axes (xyz, offset)
acc_v: vec4<f32>,
eye: vec4<f32>, // eye position, w = 1 for perspective (0: orthographic, looking along -back)
ao: vec4<f32>, // radius in world units (zero: disabled)
// analysis colours (`theme::AnalysisColors`): draft positive, between, negative; reachable,
// blocked; curvature flat, middle, tight
ana_c: array<vec4<f32>, 8>,
@@ -28,6 +29,7 @@ fn near_z(c: vec4<f32>) -> f32 {
}
@group(1) @binding(2) var acc_t: texture_2d<f32>;
@group(2) @binding(0) var ao_depth: texture_depth_2d;
fn clipped(p: vec3<f32>) -> bool {
return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w;
@@ -128,7 +130,7 @@ fn solid(i: TOut, front: bool) -> vec4<f32> {
if (u.ana.x > 0.5 && length(i.n) > 0.5) {
return analysis(i, k);
}
let c = shade(i);
let c = lit(i, occlusion(i));
// Silhouettes (styles with edges): where a curved surface turns away from the eye, a line
// about 1.5 px wide, on the visible surface only (depth-correct).
if (u.screen.w > 0.5 && length(i.n) > 0.5 && fw > 1e-6) {
@@ -138,6 +140,59 @@ fn solid(i: TOut, front: bool) -> vec4<f32> {
return c;
}
// A single-sample opaque depth map, independent of the window's MSAA and its UI offsets.
@fragment
fn fs_ao_depth(i: TOut, @builtin(front_facing) front: bool) -> @builtin(frag_depth) f32 {
if (clipped(i.wp) || length(i.n) < 0.5) { discard; }
if (!front && length(u.clip.xyz) > 0.5) { return cap_depth(i.wp, i.pos.z); }
return i.pos.z;
}
// Deterministic cosine-weighted hemisphere samples. Projecting the sample and a point one
// radius toward the eye supplies a depth range in both orthographic and perspective views;
// distant foreground geometry cannot cast a dark halo onto a background surface.
fn occlusion(i: TOut) -> f32 {
let radius = u.ao.x;
if (radius <= 0.0 || length(i.n) < 0.5) { return 1.0; }
var n = normalize(i.n);
if (dot(n, u.back.xyz) < 0.0) { n = -n; }
let axis = select(vec3<f32>(0.0, 0.0, 1.0), vec3<f32>(0.0, 1.0, 0.0), abs(n.z) > 0.9);
let tangent = normalize(cross(axis, n));
let bitangent = cross(n, tangent);
let size = vec2<i32>(textureDimensions(ao_depth));
// The map is a 1 × 1 stand-in until a frame draws into it (the product preview draws no
// prepass): sampling it tells nothing, so leave the surface unoccluded.
if (size.x < 2 || size.y < 2) { return 1.0; }
// One comparison for both depth directions: depths read as 0 near / 1 far (mirrored when
// the buffer runs reversed). The map is cleared to its far plane either way, so a texel
// with nothing in it reads as 1 and the `d < 1.0` test below skips it.
let flip = reversed();
var blocked = 0.0;
for (var j = 0u; j < 32u; j = j + 1u) {
let f = (f32(j) + 0.5) / 32.0;
let angle = f32(j) * 2.39996323;
let direction = tangent * (cos(angle) * sqrt(f)) + bitangent * (sin(angle) * sqrt(f)) + n * sqrt(1.0 - f);
let reach = radius * (0.2 + 0.8 * fract(f32(j) * 0.61803399 + 0.5));
let sample = i.wp + n * (radius * 0.025) + direction * reach;
let q = u.vp * vec4<f32>(sample, 1.0);
let near = u.vp * vec4<f32>(sample + u.back.xyz * radius, 1.0);
if (q.w <= 0.0 || near.w <= 0.0) { continue; }
let ndc = q.xyz / q.w;
let uv = vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
if (any(uv < vec2<f32>(0.0)) || any(uv >= vec2<f32>(1.0)) || ndc.z < 0.0 || ndc.z > 1.0) { continue; }
let d0 = textureLoad(ao_depth, vec2<i32>(uv * vec2<f32>(size)), 0);
let zs = select(ndc.z, 1.0 - ndc.z, flip);
let zn = select(near.z / near.w, 1.0 - near.z / near.w, flip);
let d = select(d0, 1.0 - d0, flip);
let span = max(zs - zn, 1e-7);
let delta = (zs - d) / span;
if (d < 1.0 && delta > 0.005 && delta < 1.0) {
blocked = blocked + smoothstep(0.005, 0.15, delta) * (1.0 - smoothstep(0.5, 1.0, delta));
}
}
return 1.0 - 0.85 * blocked / 32.0;
}
/// How fast the normal turns across the pixel (per mm).
fn curvature(i: TOut) -> f32 {
let nn = normalize(i.n);
@@ -230,6 +285,10 @@ fn fs_tri_all(i: TOut) -> @location(0) vec4<f32> {
}
fn shade(i: TOut) -> vec4<f32> {
return lit(i, 1.0);
}
fn lit(i: TOut, visibility: f32) -> vec4<f32> {
// A zero normal marks flat colour (selection fills, translucent planes).
if (length(i.n) < 0.5) {
return out_color(i.c);
@@ -242,7 +301,7 @@ fn shade(i: TOut) -> 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;
let k = 0.42 + 0.38 * diff + 0.25 * fill;
let k = 0.42 + 0.38 * diff + 0.25 * fill - (0.42 + 0.25 * fill) * (1.0 - visibility);
return out_color(vec4<f32>(min(i.c.rgb * k + vec3<f32>(spec), vec3<f32>(1.0)), i.c.a));
}
+64 -1
View File
@@ -6,7 +6,12 @@ use super::CommandSpec;
use crate::params::{bad, num, req_vec2, req_vec3, vec3};
use crate::{Result, Session};
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("view.navigate", "Navigate View", navigate)
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("view.graphics_preset", "Graphics Preset", graphics_preset)
.icon("settings").noundo().doc_only().params("preset: performance|quality → preset, enabled, display_quality, supersampling, supersampling_adaptive; Quality: AO, Fine, adaptive 2x SSAA; Performance: no AO, Normal, no SSAA"),
CommandSpec::new("view.ambient_occlusion", "Ambient Occlusion", ambient_occlusion)
.icon("settings").noundo().doc_only().params("enabled: bool → enabled; apply soft contact shading in the GPU viewport"),
CommandSpec::new("view.navigate", "Navigate View", navigate)
.icon("orbit")
.noundo()
.doc_only()
@@ -286,3 +291,61 @@ mod tests {
}
}
}
fn ambient_occlusion(_s: &mut Session, p: &Value) -> Result<Value> {
let enabled = p.get("enabled").and_then(Value::as_bool).ok_or_else(|| bad("view.ambient_occlusion", "enabled must be a boolean"))?;
Ok(json!({"enabled": enabled}))
}
#[cfg(test)]
mod ambient_occlusion_tests {
use super::*;
#[test]
fn validates_display_setting_without_editing_design_or_history() {
let mut s = Session::default();
let before = s.doc.to_json();
for enabled in [true, false] {
assert_eq!(s.execute("view.ambient_occlusion", &json!({"enabled": enabled})).unwrap(), json!({"enabled": enabled}));
}
for p in [json!({}), json!({"enabled": 1}), json!({"enabled": "true"}), json!({"enabled": null})] {
assert!(s.execute("view.ambient_occlusion", &p).is_err());
}
assert_eq!(s.doc.to_json(), before);
assert!(s.undo.is_empty());
}
}
/// One preset for contact shading, tessellation and supersampling. MSAA stays independent.
fn graphics_preset(_s: &mut Session, p: &Value) -> Result<Value> {
let preset = p.get("preset").and_then(Value::as_str);
let enabled = match preset {
Some("quality") => true,
Some("performance") => false,
_ => return Err(bad("view.graphics_preset", "preset must be performance or quality")),
};
Ok(json!({"preset": preset, "enabled": enabled, "display_quality": if enabled { "fine" } else { "normal" },
"supersampling": if enabled { 2.0 } else { 1.0 }, "supersampling_adaptive": true}))
}
#[cfg(test)]
mod graphics_preset_tests {
use super::*;
#[test]
fn presets_validate_without_changing_design_or_history() {
let mut s = Session::default();
let before = s.doc.to_json();
for (preset, enabled) in [("quality", true), ("performance", false)] {
assert_eq!(
s.execute("view.graphics_preset", &json!({"preset":preset})).unwrap(),
json!({"preset":preset,"enabled":enabled,"display_quality":if enabled { "fine" } else { "normal" },
"supersampling":if enabled { 2.0 } else { 1.0 },"supersampling_adaptive":true})
);
}
for params in [json!({}), json!({"preset":"fast"}), json!({"preset":true}), json!({"preset":null})] {
assert!(s.execute("view.graphics_preset", &params).is_err());
}
assert_eq!(s.doc.to_json(), before);
assert!(s.undo.is_empty());
}
}
+1
View File
@@ -325,6 +325,7 @@ fn frame(scene: &Scene, cam: &Camera, [width, height]: [u32; 2], key: u64, acces
access,
outline: true,
eye: [eye[0], eye[1], eye[2], if cam.fov > 0.0 { 1.0 } else { 0.0 }],
ao_radius: 0.0,
ssaa: 1.0,
}
}
+16 -4
View File
@@ -14,14 +14,17 @@ use wgpu::util::DeviceExt;
use crate::pbr;
mod ao;
/// Triangle vertex: position (3 × f32), normal (3 × f32), sRGB colour (4 × u8).
pub const TRI_SIZE: usize = 28;
pub const PBR_SIZE: usize = pbr::VERTEX_SIZE;
/// Line instance: a, b (3 × f32 each), colour (4 × u8), width in pixels (f32).
pub const LINE_SIZE: usize = 32;
/// The shader's `U`: the view-projection matrix, 9 `vec4`s, the 8 analysis colours, their
/// flags and the depth direction (`uniform_bytes`).
const UNIFORM_SIZE: u64 = 368;
/// The shader's `U`: the view-projection matrix, 10 `vec4`s (the tenth carries the ambient
/// occlusion radius), the 8 analysis colours, their flags and the depth direction
/// (`uniform_bytes`).
const UNIFORM_SIZE: u64 = 384;
/// A body drawn from its display plan, evaluated on the GPU: the plan, and a colour per face
/// (the plan's face numbering; faces past the end take the last colour).
@@ -245,6 +248,8 @@ pub struct Frame {
/// Eye position and 1 for a perspective camera (0: orthographic), for the section cap's depth
/// and the depth bias.
pub eye: [f32; 4],
/// World-space occlusion radius; zero skips the depth prepass and all AO sampling.
pub ao_radius: f32,
/// Supersampling (#1288): draw the frame this many times the viewport's pixels in each
/// direction and filter it down (1: off). Under 1 the frame is drawn smaller and filtered up
/// (the product preview past its pixel budget, #1464).
@@ -541,6 +546,8 @@ impl Batches {
/// The viewport's pipelines and the scenes uploaded to one device, for one kind of target.
pub struct Renderer {
/// The AO depth prepass resources (a 1 × 1 stand-in while ambient occlusion is off).
ao: ao::Resources,
tri: wgpu::RenderPipeline,
/// `tri` and `tri_cut` for planned bodies (positions and normals from the GPU evaluation,
/// colours per vertex, indexed).
@@ -959,9 +966,10 @@ impl Renderer {
count: None,
}],
});
let ao = ao::Resources::new(device, &bgl, &module, reversed);
let solid_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("sc_solid"),
bind_group_layouts: &[Some(&bgl), Some(&access_bgl)],
bind_group_layouts: &[Some(&bgl), Some(&access_bgl), Some(&ao.layout)],
immediate_size: 0,
});
let built = [Some(tri_layout())];
@@ -1108,6 +1116,7 @@ impl Renderer {
})
});
Renderer {
ao,
depth_reset,
target: t,
max_texture: device.limits().max_texture_dimension_2d,
@@ -1305,6 +1314,7 @@ impl Renderer {
res.access_bind = access_texture(device, Some(queue), &res.access_bgl, a.size, &a.depth);
res.access_version = a.version;
}
res.ao.prepare(device, encoder, &res.bind, cb.ao_radius, cb.size_px, res.target.reversed_depth(), [&res.model, &res.preview]);
// Images: upload new or changed textures, drop removed ones, rebuild the quads.
res.textures.retain(|id, _| cb.images.iter().any(|i| i.id == *id));
res.quads.clear();
@@ -1414,6 +1424,7 @@ impl Renderer {
lines(pass, &res.overlay, &m.under);
lines(pass, &res.overlay, &sk.under);
pass.set_bind_group(1, &res.access_bind, &[]);
pass.set_bind_group(2, &res.ao.bind, &[]);
let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| {
for d in &m.planned {
pass.set_pipeline(p);
@@ -1570,6 +1581,7 @@ pub fn uniform_bytes(cb: &Frame, w: f32, h: f32, linear: bool, reversed: bool) -
None => v.extend([0.0; 8]),
}
v.extend(cb.eye);
v.extend([cb.ao_radius, 0.0, 0.0, 0.0]);
v.extend(cb.analysis_colors);
v.extend([if reversed { 1.0 } else { 0.0 }, FACE_STEPS as f32, FACE_SLOPE, 0.0]);
v.iter().flat_map(|x| x.to_le_bytes()).collect()
+167
View File
@@ -0,0 +1,167 @@
//! The optional AO depth prepass. Only opaque model and preview triangles participate: their
//! depth is drawn once into a single-sample depth map the lit fragment samples for occlusion.
//! The map is independent of the window's MSAA, and the depth runs the same way as the
//! viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]).
use super::{Batches, color_layout, depth_compare, far_depth, planned_layout, tri_layout};
pub(super) struct Resources {
pub layout: wgpu::BindGroupLayout,
pub bind: wgpu::BindGroup,
depth: wgpu::TextureView,
size: [u32; 2],
pipeline: wgpu::RenderPipeline,
planned_pipeline: wgpu::RenderPipeline,
}
fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::BindGroup) {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("sc_ao_depth"),
size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let depth = texture.create_view(&Default::default());
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("sc_ao_depth"),
layout,
entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&depth) }],
});
(depth, bind)
}
impl Resources {
pub fn new(device: &wgpu::Device, uniform: &wgpu::BindGroupLayout, module: &wgpu::ShaderModule, reversed: bool) -> Self {
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("sc_ao_depth"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Depth,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("sc_ao_prepass"),
bind_group_layouts: &[Some(uniform)],
immediate_size: 0,
});
let built = [Some(tri_layout())];
let evaluated = [Some(planned_layout()), Some(color_layout())];
let pipeline = |planned: bool| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("sc_ao_prepass"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module,
entry_point: Some("vs_tri"),
buffers: if planned { &evaluated } else { &built },
compilation_options: Default::default(),
},
primitive: wgpu::PrimitiveState::default(),
depth_stencil: Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth32Float,
depth_write_enabled: Some(true),
depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module,
entry_point: Some("fs_ao_depth"),
targets: &[],
compilation_options: Default::default(),
}),
multiview_mask: None,
cache: None,
})
};
let planned_pipeline = pipeline(true);
let pipeline = pipeline(false);
let (depth, bind) = texture(device, &layout, [1, 1]);
Self { layout, bind, depth, size: [1, 1], pipeline, planned_pipeline }
}
pub fn prepare(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
uniform: &wgpu::BindGroup,
radius: f32,
size_px: [f32; 2],
reversed: bool,
batches: [&Batches; 2],
) {
let enabled = radius.is_finite() && radius > 0.0;
// Bound memory at large window sizes; normalized coordinates also handle downsampling.
let size = target_size(enabled, size_px, device.limits().max_texture_dimension_2d);
if size != self.size {
(self.depth, self.bind) = texture(device, &self.layout, size);
self.size = size;
}
if !enabled {
return;
}
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("sc_ao_prepass"),
color_attachments: &[],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: &self.depth,
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(far_depth(reversed)), store: wgpu::StoreOp::Store }),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, uniform, &[]);
for batch in batches {
pass.set_pipeline(&self.pipeline);
if let Some(tris) = &batch.tris {
for (buffer, count) in &tris.parts {
pass.set_vertex_buffer(0, buffer.slice(..));
pass.draw(0..*count, 0..1);
}
}
pass.set_pipeline(&self.planned_pipeline);
for draw in &batch.planned {
pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..));
pass.set_vertex_buffer(1, draw.colors.slice(..));
pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32);
pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1);
}
}
}
}
fn target_size(enabled: bool, pixels: [f32; 2], device_limit: u32) -> [u32; 2] {
if !enabled {
return [1, 1];
}
let limit = device_limit.clamp(1, 2048);
let pixels = pixels.map(|s| if s.is_finite() { s.max(1.0) } else { 1.0 });
let scale = (limit as f32 / pixels[0].max(pixels[1])).min(1.0);
pixels.map(|s| (s * scale).ceil().clamp(1.0, limit as f32) as u32)
}
#[cfg(test)]
mod tests {
use super::target_size;
#[test]
fn depth_map_is_bounded_and_released_when_disabled() {
assert_eq!(target_size(true, [6000.0, 3000.0], 8192), [2048, 1024]);
assert_eq!(target_size(true, [6000.0, 3000.0], 1024), [1024, 512]);
assert_eq!(target_size(false, [6000.0, 3000.0], 8192), [1, 1]);
assert_eq!(target_size(true, [f32::NAN, f32::INFINITY], 8192), [1, 1]);
assert_eq!(target_size(true, [0.0, -1.0], 8192), [1, 1]);
}
}
+1 -1
View File
@@ -97,7 +97,7 @@ fn key_from(name: &str) -> Option<egui::Key> {
fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result<Value, String> {
let r = app.run(id, params);
if r.is_ok()
&& id != "view.navigate"
&& !matches!(id, "view.navigate" | "view.ambient_occlusion" | "view.graphics_preset")
&& app.session.active_sketch.is_none()
&& app.session.world_state().bodies.len() == 1
&& app.session.undo.len() <= 2
+1
View File
@@ -281,6 +281,7 @@ fn offscreen(
access: None,
outline: false,
eye,
ao_radius: 0.0,
ssaa,
});
let texture = |format, usage| {
+13
View File
@@ -641,6 +641,14 @@ impl SolveApp {
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
self.big_operation |= now_ms() - t0 >= recovery_ui::BIG_OPERATION_MS;
if let Ok(v) = &r {
if matches!(id, "view.ambient_occlusion" | "view.graphics_preset") {
self.preferences.ambient_occlusion = v.get("enabled").and_then(Value::as_bool).unwrap_or(false);
if id == "view.graphics_preset" {
self.preferences.display_quality = v.get("display_quality").and_then(Value::as_str).unwrap_or("normal").to_string();
self.preferences.supersampling = v.get("supersampling").and_then(Value::as_f64).unwrap_or(1.0) as f32;
self.preferences.supersampling_adaptive = v.get("supersampling_adaptive").and_then(Value::as_bool).unwrap_or(true);
}
}
if id == "view.navigate" {
let to: Camera = serde_json::from_value(v.get("camera").cloned().unwrap_or_default()).map_err(|e| e.to_string())?;
if v.get("continuous").and_then(Value::as_bool).unwrap_or(false) {
@@ -734,6 +742,11 @@ impl SolveApp {
self.home.open = false;
return;
}
// A display toggle leaves the current modelling tool and camera in place.
if id == "view.ambient_occlusion" {
let _ = self.run(id, json!({"enabled": !self.preferences.ambient_occlusion}));
return;
}
// Another command ends Edit Text (its dialog is not a feature edit to keep).
sketch_text_move::cancel_drag(self);
if sketch_text::editing(self) || self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::TextMove(_))) {
@@ -127,6 +127,9 @@ fn measurement_axis_distances_can_be_disabled_saved_and_restored_in_preferences(
let mut h = vertex_measurement([0., 0., 0.], [-3., 4., -12.]);
let measurement = result(&h).clone();
h.call("ui.prefs", json!({"open":"Graphics"}));
// The graphics page scrolls; the checkbox sits below the fold since the graphics preset
// and ambient occlusion rows were added, so scroll to it as the scenario tests do.
h.call("ui.scroll", json!({"x":800.0,"y":500.0,"delta":-3000.0}));
let checkbox = crate::scenario::rect_of("prefs:measure_axis_distances").unwrap().center();
h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y}));
assert!(!h.app.preferences.measure_axis_distances);
+185 -20
View File
@@ -285,6 +285,8 @@ pub struct Prefs {
pub space_mouse_axis_speed: [f32; 6],
/// Anti-aliasing samples (applies on restart).
pub msaa: u32,
/// Soft contact shading in the GPU viewport; optional and applied immediately.
pub ambient_occlusion: bool,
/// The grid turns to the upright origin plane facing a side view (#1470). Off by default: the
/// grid stays on the ground plane (XY) whatever the view.
pub grid_follows_view: bool,
@@ -434,6 +436,7 @@ impl Default for Prefs {
space_mouse_reverse: [false; 6],
space_mouse_axis_speed: [1.0; 6],
msaa: 4,
ambient_occlusion: false,
grid_follows_view: false,
display_quality: "normal".into(),
supersampling: 1.0,
@@ -758,6 +761,7 @@ fn defaults(app: &mut SolveApp, page: usize) {
PAGE_GRAPHICS => {
let msaa = p.msaa != d.msaa;
p.msaa = d.msaa;
p.ambient_occlusion = d.ambient_occlusion;
p.display_quality = d.display_quality;
p.supersampling = d.supersampling;
p.supersampling_adaptive = d.supersampling_adaptive;
@@ -1367,6 +1371,9 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
ui.end_row();
}
4 => {
ui.label(app.tr("ui.graphics_preset"));
graphics_preset_selector(app, ui);
ui.end_row();
ui.label(crate::i18n::tr_label("Visual style"));
let styles = ["Shaded with edges", "Shaded", "Wireframe", "Shaded with hidden edges"];
let selected_label = crate::i18n::tr_label(styles[usize::from(app.ui.visual_style.min(3))]);
@@ -1386,9 +1393,35 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
ui.label(crate::i18n::tr_label("Ground shadow"));
ui.checkbox(&mut app.ui.ground_shadow, "");
ui.end_row();
ui.label(crate::i18n::tr_label("Ambient occlusion"));
ambient_occlusion_checkbox(app, ui, "");
ui.end_row();
ui.label(crate::i18n::tr_label("Perspective view"));
ui.checkbox(&mut app.ui.perspective, "");
ui.end_row();
// Keep accessibility controls visible before the longer rendering-quality controls.
ui.label("");
ui.end_row();
ui.label(RichText::new(app.tr("ui.colour_vision")).strong());
ui.label("");
ui.end_row();
ui.label(app.tr("ui.colour_vision_mode"));
let mode = app.preferences.color_vision;
let response = egui::ComboBox::from_id_salt("pref_color_vision").selected_text(app.tr(mode.label_id())).show_ui(ui, |ui| {
for m in crate::theme::ColorVision::ALL {
ui.selectable_value(&mut app.preferences.color_vision, m, crate::i18n::tr(m.label_id())).on_hover_text(crate::i18n::tr(m.help_id()));
}
});
crate::scenario::publish_handle("prefs:color_vision", response.response.rect.center());
if app.preferences.color_vision != mode {
// At once, like the theme: the next frame draws in the new colours.
ui.ctx().request_repaint();
}
ui.end_row();
ui.label(app.tr("ui.colour_vision_sample"));
colour_vision_sample(ui, t);
ui.end_row();
note(ui, app.tr("ui.colour_vision_note"));
ui.label(app.tr("ui.anti_aliasing"));
egui::ComboBox::from_id_salt("pref_msaa").selected_text(format!("{}×", app.preferences.msaa)).show_ui(ui, |ui| {
for m in MSAA {
@@ -1441,26 +1474,6 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
crate::scenario::publish_rect("prefs:measure_axis_distances", response.rect);
response.on_hover_text(app.tr("settings.measure_axis_distances_help"));
ui.end_row();
// Colour vision (#778): its own section at the end of the page.
ui.label(RichText::new(app.tr("ui.colour_vision")).strong());
ui.label("");
ui.end_row();
ui.label(app.tr("ui.colour_vision_mode"));
let mode = app.preferences.color_vision;
egui::ComboBox::from_id_salt("pref_color_vision").selected_text(app.tr(mode.label_id())).show_ui(ui, |ui| {
for m in crate::theme::ColorVision::ALL {
ui.selectable_value(&mut app.preferences.color_vision, m, crate::i18n::tr(m.label_id())).on_hover_text(crate::i18n::tr(m.help_id()));
}
});
if app.preferences.color_vision != mode {
// At once, like the theme: the next frame draws in the new colours.
ui.ctx().request_repaint();
}
ui.end_row();
ui.label(app.tr("ui.colour_vision_sample"));
colour_vision_sample(ui, t);
ui.end_row();
note(ui, app.tr("ui.colour_vision_note"));
// Last, so the colour vision section above keeps its place on the page.
ui.label("");
ui.end_row();
@@ -2486,3 +2499,155 @@ mod ui_scale_regression_tests {
assert_eq!(h.ctx.zoom_factor(), 1.0);
}
}
/// Both display-setting surfaces dispatch the same programmatic command.
pub(crate) fn ambient_occlusion_checkbox(app: &mut SolveApp, ui: &mut egui::Ui, label: &str) {
let mut enabled = app.preferences.ambient_occlusion;
let response = ui
.checkbox(&mut enabled, crate::i18n::tr_label(label))
.on_hover_text(crate::i18n::tr_label("Soft shading where opaque surfaces meet. Requires the GPU viewport."));
crate::scenario::publish_handle("view:ambient_occlusion", response.rect.center());
if response.changed() {
let _ = app.run("view.ambient_occlusion", json!({"enabled": enabled}));
}
}
#[cfg(test)]
mod ambient_occlusion_tests {
use super::*;
#[test]
fn ambient_occlusion_is_optional_persistent_and_cancelable() {
let old: Prefs = serde_json::from_value(json!({"msaa": 4})).unwrap();
assert!(!old.ambient_occlusion);
let mut h = crate::scenario::Harness::new();
let camera = h.app.cam;
let design = h.app.session.doc.to_json();
h.call("ui.prefs", json!({"open":"Graphics"}));
let checkbox = crate::scenario::handle_at("view:ambient_occlusion").unwrap();
h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y}));
assert!(h.app.preferences.ambient_occlusion);
let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
restored.load_prefs(&h.app.prefs());
assert!(restored.preferences.ambient_occlusion);
h.call("ui.prefs", json!({"button":"cancel"}));
assert!(!h.app.preferences.ambient_occlusion);
h.call("ui.prefs", json!({"open":"Graphics", "ambient_occlusion":true}));
h.call("ui.prefs", json!({"button":"apply"}));
h.call("ui.prefs", json!({"button":"defaults"}));
assert!(!h.app.preferences.ambient_occlusion);
h.call("ui.prefs", json!({"button":"cancel"}));
assert!(h.app.preferences.ambient_occlusion);
h.call("engine.execute", json!({"command":"view.ambient_occlusion","params":{"enabled":false}}));
assert!(!h.app.preferences.ambient_occlusion);
h.call("engine.execute", json!({"command":"view.ambient_occlusion","params":{"enabled":"yes"}}));
assert!(!h.app.preferences.ambient_occlusion);
h.app.start("view.ambient_occlusion");
assert!(h.app.preferences.ambient_occlusion);
assert_eq!(h.app.cam, camera);
assert_eq!(h.app.session.doc.to_json(), design);
assert!(h.app.session.undo.is_empty());
}
}
/// Manual edits are preserved and shown as Custom rather than claiming to match a preset.
fn graphics_preset(prefs: &Prefs) -> &'static str {
match (prefs.ambient_occlusion, prefs.display_quality.as_str(), prefs.supersampling, prefs.supersampling_adaptive) {
(false, "normal", 1.0, _) => "performance",
(true, "fine", 2.0, true) => "quality",
_ => "custom",
}
}
pub(crate) fn graphics_preset_selector(app: &mut SolveApp, ui: &mut egui::Ui) {
let current = graphics_preset(&app.preferences);
let label = format!("ui.graphics_{current}");
let response = egui::ComboBox::from_id_salt("graphics_preset")
.selected_text(app.tr(&label))
.show_ui(ui, |ui| {
for (preset, label) in [("performance", "ui.graphics_performance"), ("quality", "ui.graphics_quality")] {
let item = ui.selectable_label(current == preset, app.tr(label));
crate::scenario::publish_handle(&format!("view:graphics_preset:{preset}"), item.rect.center());
if item.clicked() {
let _ = app.run("view.graphics_preset", json!({"preset":preset}));
}
}
})
.response
.on_hover_text(app.tr("ui.graphics_preset_help"));
crate::scenario::publish_handle("view:graphics_preset", response.rect.center());
}
#[cfg(test)]
mod graphics_preset_tests {
use super::*;
#[test]
fn viewport_preset_popup_accepts_quality_and_performance() {
let mut h = crate::scenario::Harness::new();
h.call("ui.inspect", json!({}));
for handle in ["nav:view", "view:graphics_preset", "view:graphics_preset:quality"] {
let pos = crate::scenario::handle_at(handle).unwrap();
h.call("ui.click", json!({"x":pos.x,"y":pos.y}));
}
assert!(h.app.preferences.ambient_occlusion);
for handle in ["view:graphics_preset", "view:graphics_preset:performance"] {
let pos = crate::scenario::handle_at(handle).unwrap();
h.call("ui.click", json!({"x":pos.x,"y":pos.y}));
}
assert!(!h.app.preferences.ambient_occlusion);
}
#[test]
fn quality_selector_enables_ao_and_supports_persistence_and_cancel() {
let mut h = crate::scenario::Harness::new();
let camera = h.app.cam;
let design = h.app.session.doc.to_json();
let msaa = h.app.preferences.msaa;
h.call("ui.prefs", json!({"open":"Graphics"}));
for handle in ["view:graphics_preset", "view:graphics_preset:quality"] {
let pos = crate::scenario::handle_at(handle).unwrap();
h.call("ui.click", json!({"x":pos.x,"y":pos.y}));
}
assert!(h.app.preferences.ambient_occlusion);
let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
restored.load_prefs(&h.app.prefs());
assert!(restored.preferences.ambient_occlusion);
h.call("ui.prefs", json!({"button":"cancel"}));
assert_eq!(graphics_preset(&h.app.preferences), "performance");
assert!(!h.app.preferences.ambient_occlusion);
h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}}));
assert!(h.app.preferences.ambient_occlusion);
h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"invalid"}}));
assert!(h.app.preferences.ambient_occlusion);
h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"performance"}}));
assert!(!h.app.preferences.ambient_occlusion);
assert_eq!(graphics_preset(&h.app.preferences), "performance");
assert_eq!(h.app.preferences.display_quality, "normal");
assert_eq!(h.app.preferences.supersampling, 1.0);
h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}}));
assert_eq!(graphics_preset(&h.app.preferences), "quality");
assert_eq!(h.app.preferences.display_quality, "fine");
assert_eq!(h.app.preferences.supersampling, 2.0);
assert!(h.app.preferences.supersampling_adaptive);
for edit in [
json!({"display_quality":"ultra"}),
json!({"supersampling":1.5}),
json!({"supersampling_adaptive":false}),
json!({"ambient_occlusion":false}),
] {
h.call("engine.execute", json!({"command":"view.graphics_preset","params":{"preset":"quality"}}));
h.call("ui.prefs", edit);
assert_eq!(graphics_preset(&h.app.preferences), "custom");
}
assert_eq!(graphics_preset(&restored.preferences), "quality");
h.call("ui.prefs", json!({"open":"Graphics"}));
h.call("ui.prefs", json!({"button":"defaults"}));
assert_eq!(graphics_preset(&h.app.preferences), "performance");
h.call("ui.prefs", json!({"button":"ok"}));
assert_eq!(h.app.preferences.msaa, msaa);
assert_eq!(h.app.cam, camera);
assert_eq!(h.app.session.doc.to_json(), design);
assert!(h.app.session.undo.is_empty());
}
}
+2
View File
@@ -538,6 +538,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
analysis_colors: [0.0; 36],
access: None,
outline: false,
// Product rendering has its own lighting; AO is a Design viewport setting.
ao_radius: 0.0,
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 },
});
+14 -2
View File
@@ -2420,6 +2420,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
analysis_colors: crate::gpu::analysis_colors(&t.analysis),
access: crate::access::map(app),
outline: matches!(app.ui.visual_style, 0 | 3),
ao_radius: if app.preferences.ambient_occlusion && app.ui.visual_style != 2 {
(model_bounds(app).diagonal() * 0.04).clamp(1e-4, 1e6) as f32
} else {
0.0
},
eye: {
let e = proj.cam.eye().to_f32();
[e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]
@@ -3446,7 +3451,7 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
("home", "Home view"),
("perspective", "Perspective / orthographic"),
("style", "Visual style: shaded with edges, shaded, wireframe, shaded with hidden edges"),
("settings", "View settings: grid, ground shadow, agent cursor"),
("settings", "View settings: grid, ground shadow, ambient occlusion, agent cursor"),
];
let menu_id = ui.id().with("nav_view_menu");
let mut menu_open = ui.data(|d| d.get_temp::<bool>(menu_id)).unwrap_or(false);
@@ -3519,6 +3524,8 @@ fn nav_bar(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) {
/// The View settings above the navigation bar's last button: grid, ground shadow and the agent
/// cursor (#35). False once it should close (a click outside it).
fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool {
// A preset dropdown extends beyond this menu; let it consume its own clicks.
let child_popup_open = egui::Popup::is_any_open(ui.ctx());
let area = crate::frame::area(egui::Id::new("sc_view_menu"))
.order(egui::Order::Foreground)
.pivot(Align2::RIGHT_BOTTOM)
@@ -3527,8 +3534,12 @@ fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.set_width(220.0);
ui.label(egui::RichText::new(crate::i18n::tr_label("VIEW")).strong().size(11.5));
ui.label(app.tr("ui.graphics_preset"));
crate::prefs::graphics_preset_selector(app, ui);
ui.separator();
ui.checkbox(&mut app.ui.show_grid, crate::i18n::tr_label("Grid"));
ui.checkbox(&mut app.ui.ground_shadow, crate::i18n::tr_label("Ground shadow"));
crate::prefs::ambient_occlusion_checkbox(app, ui, "Ambient occlusion");
ui.separator();
let s = &mut app.ui.agent_cursor;
let show = ui.checkbox(&mut s.show, crate::i18n::tr_label("Show Agent Cursor"));
@@ -3553,7 +3564,8 @@ fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool {
}
});
});
let clicked_out = ui.input(|i| i.pointer.any_pressed())
let clicked_out = !child_popup_open
&& ui.input(|i| i.pointer.any_pressed())
&& ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| !r.response.rect.contains(p) && !button.contains(p));
!clicked_out
}
@@ -1,25 +1,22 @@
[
{"note": "#778: Preferences › Graphics › Colour vision. A mode applies at once, Cancel puts it back, OK keeps it, Restore Defaults on Graphics resets it, and the window keeps its size."},
{"note": "#778: Preferences › Graphics › Colour vision. A mode applies at once, Cancel puts it back, OK keeps it, Restore Defaults on Graphics resets it, and the window keeps its size. The accessibility controls sit above the longer rendering-quality rows, so nothing here needs scrolling."},
{"click": {"handle": "titlebar:preferences"}},
{"expect": {"prefs": {"dialog": "General", "color_vision": "off"}, "same_width": "prefs:window"}},
{"widget": "Graphics"},
{"call": "ui.scroll", "params": {"x": 800, "y": 500, "delta": -3000}},
{"expect": {"shown": "Colour vision", "prefs": {"dialog": "Graphics"}, "same_width": "prefs:window"}},
{"widget": "Off"},
{"click": {"handle": "prefs:color_vision"}},
{"widget": "Deutan"},
{"expect": {"prefs": {"color_vision": "deutan"}, "same_width": "prefs:window"}},
{"widget": "Cancel"},
{"expect": {"prefs": {"dialog": null, "color_vision": "off"}}},
{"key": "Comma", "cmd": true},
{"widget": "Graphics"},
{"call": "ui.scroll", "params": {"x": 800, "y": 500, "delta": -3000}},
{"widget": "Off"},
{"click": {"handle": "prefs:color_vision"}},
{"widget": "Tritan"},
{"widget": "OK"},
{"expect": {"prefs": {"dialog": null, "color_vision": "tritan"}}},
{"key": "Comma", "cmd": true},
{"widget": "Graphics"},
{"call": "ui.scroll", "params": {"x": 800, "y": 500, "delta": -3000}},
{"expect": {"shown": "Tritan", "same_width": "prefs:window"}},
{"widget": "Restore Defaults"},
{"expect": {"prefs": {"color_vision": "off"}}},
+101
View File
@@ -0,0 +1,101 @@
# Ambient occlusion
Enable **Ambient occlusion** in the viewport's **View settings** menu or in
**Preferences → Graphics**. It adds soft contact shading at corners, recesses and
nearby opaque surfaces. It is off by default, applies immediately, and is saved
between runs. The shared **Graphics Preset** selector in both settings surfaces
combines AO with the display-quality and supersampling controls from #1319 and #1321:
| Preset | Ambient occlusion | Display quality | Supersampling |
|---|---|---|---|
| Performance (default) | Off | Normal | Off (1×) |
| Quality | On | Fine | 2×, only while the view is still |
| Custom | Your manual combination | Your manual combination | Your manual combination |
Custom is derived from the current settings, not a third preset that overwrites them.
Individual controls remain editable. Selecting a preset applies all three settings
immediately; MSAA, ground shadow, projection and visual style stay unchanged.
Graphics preferences support Cancel, Apply and Restore Defaults. Adaptive supersampling
keeps #1321's 0.25-second settling delay, texture limit and 384 MiB memory cap;
the requested 2× may be reduced or skipped when the device cannot accommodate it.
The control channel and connected MCP clients can use the same command as the UI:
```json
{"command":"view.ambient_occlusion","params":{"enabled":true}}
```
`view.graphics_preset {"preset":"quality"}` (or `"performance"`) selects the preset.
`ui.prefs {"ambient_occlusion": true}` also sets the preference. The command changes
only display preferences, without adding a modelling undo step or moving the camera.
The GPU viewport uses 32 deterministic hemisphere samples per shaded pixel against
an opaque depth prepass (at most 2048 pixels on its longest side). The radius follows
model size, and depth-range rejection avoids shadows from distant foreground objects.
It supports orthographic and perspective cameras and respects section clipping.
Wireframe, transparent bodies, overlays and surface-analysis colours are unaffected.
Disabling it skips the depth prepass and sampling and releases the full-size depth map.
This is screen-space shading: off-screen and hidden surfaces cannot contribute.
The software fallback and CPU model snapshots do not apply this GPU effect. Capture
the actual window with `ui.screenshot` when reviewing it.
## Metal startup comparison (2026-10-15)
On an Apple M3 Pro (18-core GPU, 36 GiB unified memory), macOS 27.0
(26A428), both unchanged main `0872eb95` and this branch merged with that
revision reproduce the same startup defect: `solidcraft --sample` shows the
plate's edges and ground shadow but no opaque faces. AO is disabled on the
branch and does not exist on main. Both were built with `--profile ci`, launched
separately on Metal with MSAA 4x, and captured at 1200 × 850 logical pixels
(2400 × 1700 physical pixels). Their viewport captures are pixel-identical.
This establishes that the symptom also exists on main; this PR does not fix it.
For the AO comparison screenshots and timings below, the display mesh was
rebuilt by assigning the sample Plate opacity 0.99 and then restoring it to 1.0
(with the same colour, `#a6b0bd`). Measurements use opaque faces, GPU
tessellation and the actual native viewport after that rebuild. The screenshots
are attached in the review conversation, rather than committed as generated assets.
## AO-only rendering performance (2026-10-15)
These measurements predate the combined presets. They isolate AO at Normal
tessellation with supersampling off; they are **not** timings for the combined
Quality preset, which also requests Fine tessellation and adaptive 2× supersampling.
Same M3 Pro / macOS machine and `ci` build profile as above (not a release-build
claim). Window: 2400 × 1700 physical pixels; model viewport: 1900 × 1312.
Orthographic home view, shaded with edges, MSAA 4x, normal display quality,
supersampling off, ground shadow on, grid/origin/sketches hidden. The heavier
design is a rectangular body pattern of the sample: 5 × 5 plates, X spacing
90 mm, Y spacing 60 mm, fitted to the viewport (25 opaque bodies).
These are **completed render-work milliseconds per frame**, not the UI-only
`ui.inspect.frame_ms` or a claimed display FPS. Temporary native instrumentation
measured from the beginning of `paint_and_update_textures` through command
submission and `device.poll(PollType::wait_indefinitely())`. The renderer's
accumulated surface-acquisition/queue-submit timing was subtracted; presentation
and UI layout are excluded. This includes CPU render preparation and waiting
for GPU completion. Continuous repaint was enabled. Instrumentation was removed
from the source after building the measurement binary.
Each design ran three alternating Performance/Quality pairs: 2 seconds warm-up
after each switch, then 3 seconds recorded. No builds ran during measurement.
The table pools the recorded frames; p95 exposes variability on this shared
desktop. It is a local comparative measurement, not a hardware-independent FPS
guarantee or a modelling/recompute benchmark.
| Design | Preset | Frames | Median render ms | p95 render ms |
|---|---|---:|---:|---:|
| sample | performance | 1082 | 2.52 | 2.65 |
| sample | quality | 1077 | 6.35 | 7.27 |
| 25-plates | performance | 1074 | 3.15 | 3.45 |
| 25-plates | quality | 1082 | 6.93 | 7.50 |
Per-trial medians (ms), in chronological order:
- sample-performance: 2.53, 2.47, 2.53.
- sample-quality: 5.82, 4.48, 7.08.
- 25-plates-performance: 3.13, 3.16, 3.14.
- 25-plates-quality: 6.80, 7.02, 6.95.
+22 -19
View File
@@ -4,7 +4,7 @@
//! label, id and toolbar place. It comes only from SolidCraft's command registry
//! (`solidcraft-cli commands`), so it can't drift from what the program does; it compares with
//! nothing else. Planned commands (registered, not built yet) are listed as planned, with their
//! issue, and are not counted.
//! issue. Counts are omitted so unrelated command additions do not edit shared headers.
use std::path::Path;
@@ -61,25 +61,18 @@ pub fn page(cmds: &[Value]) -> String {
order.push((p.clone(), format!("`{p}.*`")));
}
let planned = |c: &Value| c["planned"].as_str().map(str::to_string);
let built = cmds.iter().filter(|c| planned(c).is_none()).count();
let later = match cmds.len() - built {
0 => String::new(),
n => format!(" Planned (registered, not built yet): {n}."),
};
let mut md = format!(
// Counts made every command addition edit the same header, even across unrelated areas.
// Keep generated text local to each command so parallel branches merge cleanly more often.
let mut md = String::from(
"# Features\n\nSolidCraft's commands by area, generated by `cargo xtask features` from the command registry \
(`solidcraft-cli commands`). **{built} commands.**{later} Every command runs the same way from the toolbar, a script, \
(`solidcraft-cli commands`). Planned commands are marked in their rows. Every command runs the same way from the toolbar, a script, \
`solidcraft-cli exec <id> '<json>'`, the control channel and MCP; parameters are in the \
[command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md).\n"
[command reference](book/src/reference/commands.md) (`cargo xtask book`). Status and plans: [ROADMAP](../ROADMAP.md).\n",
);
for (prefix, heading) in &order {
let in_area: Vec<&Value> = cmds.iter().filter(|c| area(&s(c, "id")) == prefix).collect();
let n = in_area.iter().filter(|c| planned(c).is_none()).count();
let count = match in_area.len() - n {
0 => n.to_string(),
p => format!("{n}, {p} planned"),
};
md += &format!("\n## {heading} ({count})\n\n| Command | Id | Toolbar |\n|---|---|---|\n");
let mut in_area: Vec<&Value> = cmds.iter().filter(|c| area(&s(c, "id")) == prefix).collect();
in_area.sort_by_key(|c| s(c, "id"));
md += &format!("\n## {heading}\n\n| Command | Id | Toolbar |\n|---|---|---|\n");
for c in in_area {
let place = match (s(c, "tab"), s(c, "panel")) {
(t, _) if t.is_empty() => "–".to_string(),
@@ -108,12 +101,22 @@ mod tests {
)
.unwrap();
let md = page(cmds.as_array().unwrap());
assert!(md.contains("**3 commands.** Planned (registered, not built yet): 1."));
let (sk, so, other) =
(md.find("## Sketch (1)").unwrap(), md.find("## Solid modelling (1, 1 planned)").unwrap(), md.find("## `view.*` (1)").unwrap());
assert!(md.contains("Planned commands are marked in their rows."));
let (sk, so, other) = (md.find("## Sketch").unwrap(), md.find("## Solid modelling").unwrap(), md.find("## `view.*`").unwrap());
assert!(sk < so && so < other);
assert!(md.contains("| Extrude (E) | `solid.extrude` | SOLID › CREATE |"));
assert!(md.contains("| Fit | `view.fit` | – |"));
assert!(md.contains("| Knit *(planned: [#9](https://github.com/bherbruck/solidcraft/issues/9))* | `solid.knit` | SOLID › CREATE |"));
}
#[test]
fn unrelated_additions_do_not_rewrite_existing_lines_and_order_is_stable() {
let commands = vec![serde_json::json!({"id":"view.zoom","label":"Zoom"}), serde_json::json!({"id":"view.fit","label":"Fit"})];
let before = page(&commands);
let mut reordered = commands.clone();
reordered.reverse();
assert_eq!(before, page(&reordered));
reordered.push(serde_json::json!({"id":"view.pan","label":"Pan"}));
let after = page(&reordered);
assert_eq!(before, after.lines().filter(|l| !l.contains("`view.pan`")).collect::<Vec<_>>().join("\n") + "\n");
}
}