SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Performance overlay: frame-time graph and histogram, triangles, draw calls (#2548) (#2549)
fugazister4b119dd471f0
diff --git a/assets/locales/cs.json b/assets/locales/cs.jsonindex f3a12aaeac..d575a17b7e 100644--- a/assets/locales/cs.json+++ b/assets/locales/cs.json@@ -998,6 +998,16 @@"pattern.direction_1": "Směr 1","pattern.direction_2": "Směr 2","pattern.flip_direction": "Převrátit směr",+ "perf.click_for_details": "Klikněte pro podrobnosti: graf časů snímků, histogram a co vykreslila GPU",+ "perf.draw_calls": "Volání vykreslení",+ "perf.line_segments": "Úsečky",+ "perf.low_1": "1% minimum",+ "perf.renderer": "Vykreslování",+ "perf.scene_build": "Sestavení scény",+ "perf.triangles": "Trojúhelníky",+ "perf.ui_time": "Čas UI",+ "perf.viewport": "Pohled",+ "perf.worst": "nejhorší","pick a hole to seat it, or OK places it at the origin": "vyberte otvor pro usazení, nebo OK umístí do počátku","pick one or two vertices, edges or faces": "vyberte jeden nebo dva vrcholy, hrany či plochy","prefs.cpu": "CPU (softwarově)",@@ -1222,6 +1232,7 @@"search.try": "Zadejte název příkazu, prvek v tomto návrhu nebo parametr. Chcete-li spustit příkaz s hodnotami, zadejte jeho id a objekt JSON: {example}","search.valid": "Platné","settings.display_quality_note": "Jemnější úrovně kreslí zakřivené plochy a hrany hladčeji, ale síťování trvá déle. Mění se jen zobrazení, nikdy návrh ani exporty.",+ "settings.frame_rate_details_note": "Přidá graf časů posledních snímků s vykreslenými trojúhelníky, histogram časů snímků a to, co vykreslila GPU. Kliknutím na snímkovou frekvenci v pohledu je zobrazíte nebo skryjete.","settings.frame_rate_note": "Zobrazuje snímky za sekundu v pravém dolním rohu pohledu.","settings.measure_axis_distances": "Zobrazit vzdálenosti X/Y/Z","settings.measure_axis_distances_help": "Při otevřeném měření zobrazit kromě celkové vzdálenosti i složky ve směru os.",@@ -1755,6 +1766,7 @@"ui.flip": "Převrátit","ui.format": "Formát","ui.frame_rate": "Snímková frekvence",+ "ui.frame_rate_details": "Podrobnosti snímkové frekvence","ui.front": "Zepředu","ui.fully_constrained": "Plně zavazbeno","ui.function": "Funkce",diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 47796f4298..be64fddb5a 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -1301,6 +1301,16 @@"pattern.direction_1": "Direction 1","pattern.direction_2": "Direction 2","pattern.flip_direction": "Flip direction",+ "perf.click_for_details": "Click for details: frame-time graph, histogram and what the GPU drew",+ "perf.draw_calls": "Draw calls",+ "perf.line_segments": "Line segments",+ "perf.low_1": "1% low",+ "perf.renderer": "Renderer",+ "perf.scene_build": "Scene build",+ "perf.triangles": "Triangles",+ "perf.ui_time": "UI time",+ "perf.viewport": "Viewport",+ "perf.worst": "worst","pick a hole to seat it, or OK places it at the origin": "pick a hole to seat it, or OK places it at the origin","pick one or two vertices, edges or faces": "pick one or two vertices, edges or faces","prefs.add_item": "Add the item",@@ -2053,6 +2063,7 @@"search.valid": "Valid","section.off_hint": "No plane picked: OK turns the section off.","settings.display_quality_note": "Only the display. Designs and exports are not affected.",+ "settings.frame_rate_details_note": "Adds a graph of the last frames' times with the triangles drawn over it, a histogram of frame times and what the GPU drew. Click the frame rate in the view to show or hide them.","settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner.","settings.measure_axis_distances": "Show X/Y/Z distances","settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.",@@ -2621,6 +2632,7 @@"ui.flip": "Flip","ui.format": "Format","ui.frame_rate": "Frame rate",+ "ui.frame_rate_details": "Frame rate details","ui.front": "Front","ui.fully_constrained": "Fully constrained","ui.function": "Function",diff --git a/assets/locales/it.json b/assets/locales/it.jsonindex da60278fbb..fa8a593de8 100644--- a/assets/locales/it.json+++ b/assets/locales/it.json@@ -998,6 +998,16 @@"pattern.direction_1": "Direzione 1","pattern.direction_2": "Direzione 2","pattern.flip_direction": "Inverti direzione",+ "perf.click_for_details": "Fai clic per i dettagli: grafico dei tempi, istogramma e ciò che la GPU ha disegnato",+ "perf.draw_calls": "Chiamate di disegno",+ "perf.line_segments": "Segmenti",+ "perf.low_1": "1% più lento",+ "perf.renderer": "Renderer",+ "perf.scene_build": "Costruzione scena",+ "perf.triangles": "Triangoli",+ "perf.ui_time": "Tempo UI",+ "perf.viewport": "Vista",+ "perf.worst": "peggiore","pick a hole to seat it, or OK places it at the origin": "seleziona un foro in cui inserirlo, oppure premi OK per posizionarlo nell'origine","pick one or two vertices, edges or faces": "seleziona uno o due vertici, spigoli o facce","prefs.cpu": "CPU (software)",@@ -1073,6 +1083,7 @@"search.try": "Digita il nome di un comando, una feature di questo progetto o un parametro. Per eseguire un comando con dei valori, digita il suo id e un oggetto JSON: {example}","search.valid": "Valido","settings.display_quality_note": "I livelli più fini rendono più uniformi le facce curve e gli spigoli e richiedono più tempo per la mesh. Cambia solo la vista, mai il progetto o le esportazioni.",+ "settings.frame_rate_details_note": "Aggiunge un grafico dei tempi degli ultimi fotogrammi con i triangoli disegnati sopra, un istogramma dei tempi dei fotogrammi e ciò che la GPU ha disegnato. Fai clic sulla frequenza nella vista per mostrarli o nasconderli.","settings.frame_rate_note": "Mostra i fotogrammi al secondo nell'angolo inferiore destro della vista.","settings.measure_axis_distances": "Mostra distanze X/Y/Z","settings.measure_axis_distances_help": "Mostra le componenti lungo gli assi globali accanto alla distanza totale quando Misura è aperto.",@@ -1602,6 +1613,7 @@"ui.flip": "Inverti","ui.format": "Formato","ui.frame_rate": "Frequenza dei fotogrammi",+ "ui.frame_rate_details": "Dettagli della frequenza dei fotogrammi","ui.front": "Frontale","ui.fully_constrained": "Completamente vincolato","ui.function": "Funzione",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 601bf3c86a..d165980834 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -1301,6 +1301,16 @@"pattern.direction_1": "方向 1","pattern.direction_2": "方向 2","pattern.flip_direction": "方向を反転",+ "perf.click_for_details": "クリックで詳細: フレーム時間のグラフ、ヒストグラム、GPU の描画内容",+ "perf.draw_calls": "描画コール",+ "perf.line_segments": "線分",+ "perf.low_1": "下位 1%",+ "perf.renderer": "レンダラー",+ "perf.scene_build": "シーン構築",+ "perf.triangles": "三角形",+ "perf.ui_time": "UI 時間",+ "perf.viewport": "ビュー",+ "perf.worst": "最悪","pick a hole to seat it, or OK places it at the origin": "配置先の穴を選択するか、[OK]を押すと原点に配置します。","pick one or two vertices, edges or faces": "1つまたは2つの頂点、エッジ、面を選択","prefs.add_item": "項目を追加",@@ -2053,6 +2063,7 @@"search.valid": "有効","section.off_hint": "平面が選択されていません。OK を押すとセクションを解除します。","settings.display_quality_note": "表示だけに影響します。設計や書き出しは変わりません。",+ "settings.frame_rate_details_note": "直近のフレーム時間のグラフ(描画した三角形数を重ねて表示)、フレーム時間のヒストグラム、GPU が描画した内容を追加します。ビューのフレームレートをクリックすると表示/非表示を切り替えます。","settings.frame_rate_note": "ビューの右下に 1 秒あたりのフレーム数を表示します。","settings.measure_axis_distances": "計測のX・Y・Z距離を表示","settings.measure_axis_distances_help": "計測ダイアログを開いている間、2点間距離に加えてワールドX・Y・Z軸方向の寸法線と距離を表示します。",@@ -2621,6 +2632,7 @@"ui.flip": "反転","ui.format": "形式","ui.frame_rate": "フレームレート",+ "ui.frame_rate_details": "フレームレートの詳細","ui.front": "正面","ui.fully_constrained": "完全拘束","ui.function": "関数",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex 215c64cb58..2313f2fbd2 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -1301,6 +1301,16 @@"pattern.direction_1": "方向 1","pattern.direction_2": "方向 2","pattern.flip_direction": "反转方向",+ "perf.click_for_details": "点击查看详情:帧耗时图、直方图和 GPU 绘制的内容",+ "perf.draw_calls": "绘制调用",+ "perf.line_segments": "线段",+ "perf.low_1": "1% 最低",+ "perf.renderer": "渲染器",+ "perf.scene_build": "场景构建",+ "perf.triangles": "三角形",+ "perf.ui_time": "界面耗时",+ "perf.viewport": "视图",+ "perf.worst": "最差","pick a hole to seat it, or OK places it at the origin": "选择一个孔放置,或单击确定放置在原点","pick one or two vertices, edges or faces": "选择一个或两个顶点、边或面","prefs.add_item": "添加项目",@@ -2053,6 +2063,7 @@"search.valid": "有效","section.off_hint": "未选择平面:按“确定”将移除剖面。","settings.display_quality_note": "仅影响显示,不影响设计和导出。",+ "settings.frame_rate_details_note": "添加最近各帧耗时的图表(叠加绘制的三角形数)、帧耗时直方图以及 GPU 绘制的内容。点击视图中的帧率可显示或隐藏。","settings.frame_rate_note": "在视图右下角显示每秒帧数。","settings.measure_axis_distances": "显示 X/Y/Z 距离","settings.measure_axis_distances_help": "测量对话框打开时,在总距离之外显示沿世界坐标轴方向的尺寸线和距离。",@@ -2621,6 +2632,7 @@"ui.flip": "翻转","ui.format": "格式","ui.frame_rate": "帧率",+ "ui.frame_rate_details": "帧率详情","ui.front": "前视","ui.fully_constrained": "完全约束","ui.function": "函数",diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rsindex 26955aaea6..940dfe7351 100644--- a/crates/gpu/src/capture.rs+++ b/crates/gpu/src/capture.rs@@ -293,6 +293,12 @@ impl Capturer {Ok(rgba)}+ /// What the last picture drew ([`crate::view::DrawStats`]).+ pub fn last_stats(&self) -> crate::view::DrawStats {+ let Ok(state) = self.state.lock() else { return Default::default() };+ state.renderer.stats().lock().map(|s| *s).unwrap_or_default()+ }+/// [`Capturer::rgba`] as PNG bytes.pub fn png(&self, scene: &Scene, cam: &Camera, width: u32, height: u32) -> Result<Vec<u8>> {let rgba = self.rgba(scene, cam, width, height)?;diff --git a/crates/gpu/src/view.rs b/crates/gpu/src/view.rsindex 306efb095b..966d29c03c 100644--- a/crates/gpu/src/view.rs+++ b/crates/gpu/src/view.rs@@ -40,6 +40,52 @@ pub struct PlannedBody {pub face_colors: Vec<[u8; 4]>,}+/// What the viewport's last frame drew, counted as it was drawn (the performance overlay, #2548).+/// Triangles and line segments count every pass that draws them, so a section's stencil passes+/// count twice; that is the work the GPU did.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct DrawStats {+ pub draw_calls: u32,+ pub triangles: u64,+ pub line_segments: u64,+ /// The frame was drawn supersampled and filtered down.+ pub supersampled: bool,+}++/// The renderer's last [`DrawStats`], shared with the UI that shows them.+pub type DrawStatsHandle = Arc<Mutex<DrawStats>>;++/// Counts a frame's draw calls as they are made (shared by the drawing closures, hence the cells).+#[derive(Default)]+pub(crate) struct Tally {+ calls: std::cell::Cell<u32>,+ triangles: std::cell::Cell<u64>,+ segments: std::cell::Cell<u64>,+}++impl Tally {+ /// A draw call of `vertices` triangle corners (or indices), `instances` times.+ fn triangles(&self, vertices: u32, instances: u32) {+ self.call();+ self.triangles.set(self.triangles.get().saturating_add(u64::from(vertices / 3) * u64::from(instances)));+ }++ /// A draw call of `n` line segments.+ fn segments(&self, n: u32) {+ self.call();+ self.segments.set(self.segments.get().saturating_add(u64::from(n)));+ }++ /// A draw call that counts neither (a full-screen pass).+ fn call(&self) {+ self.calls.set(self.calls.get().saturating_add(1));+ }++ fn stats(&self) -> DrawStats {+ DrawStats { draw_calls: self.calls.get(), triangles: self.triangles.get(), line_segments: self.segments.get(), supersampled: false }+ }+}+/// A quick hasher for welding (the keys are coordinates' bits, from the design, not chosen to/// collide): the standard one made welding a 2 M-triangle scan take half a second.#[derive(Default)]@@ -792,17 +838,17 @@ struct InstancedDraw {impl InstancedDraw {/// Draw every placement in view, from its level, with `smooth` or `flat` as the level's/// triangles are lit.- pub(crate) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline) {+ pub(crate) fn draw(&self, pass: &mut wgpu::RenderPass<'_>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline, tally: &Tally) {for level in &self.levels {pass.set_pipeline(if level.flat { flat } else { smooth });- level.draw(pass);+ level.draw(pass, tally);}}}impl LevelDraw {/// Draw its placements (in vertex buffer 1).- fn draw(&self, pass: &mut wgpu::RenderPass<'_>) {+ fn draw(&self, pass: &mut wgpu::RenderPass<'_>, tally: &Tally) {if self.count == 0 {return;}@@ -812,11 +858,13 @@ impl LevelDraw {pass.set_vertex_buffer(0, vertices.slice(..));pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);pass.draw_indexed(0..*count, 0, 0..self.count);+ tally.triangles(*count, self.count);}SharedGpu::Unshared(batch) => {for (buffer, count) in &batch.parts {pass.set_vertex_buffer(0, buffer.slice(..));pass.draw(0..*count, 0..self.count);+ tally.triangles(*count, self.count);}}}@@ -1109,6 +1157,11 @@ impl Batches {/// The viewport's pipelines and the scenes uploaded to one device, for one kind of target.pub struct Renderer {+ /// What the last frame drew ([`Renderer::stats`]).+ stats: DrawStatsHandle,+ /// What the frame `prepare` drew offscreen (supersampled, or for see-through surfaces),+ /// published when `paint` copies it into the view.+ ss_stats: DrawStats,/// The AO depth prepass resources (a 1 × 1 stand-in while ambient occlusion is off).ao: ao::Resources,tri: wgpu::RenderPipeline,@@ -1854,6 +1907,8 @@ impl Renderer {ss_bgl,ss: None,ss_ready: false,+ stats: DrawStatsHandle::default(),+ ss_stats: DrawStats::default(),ss_key: None,cached: None,image,@@ -2114,9 +2169,12 @@ impl Renderer {let key = frame_key(cb);if can_reuse(res.ss_ready && res.ss.is_some(), res.ss_key, key) {// A still frame shows the picture as it is; the first one filters it down once.- if res.ss_scaled && res.cached.is_none() {+ let filter = res.ss_scaled && res.cached.is_none();+ if filter {res.cache_picture(device, encoder, cb.size_px);}+ // The scene isn't drawn again: `paint`'s blit (and that filter) is all this frame draws.+ res.ss_stats = DrawStats { draw_calls: u32::from(filter), ..DrawStats::default() };return;}res.cached = None;@@ -2222,13 +2280,28 @@ impl Renderer {pass.set_bind_group(0, &ss.bind, &[]);}pass.draw(0..3, 0..1);+ self.publish(DrawStats { draw_calls: self.ss_stats.draw_calls + 1, supersampled: self.ss_scaled, ..self.ss_stats });return;}+ let tally = Tally::default();if let Some(reset) = &self.depth_reset {pass.set_pipeline(reset);pass.draw(0..3, 0..1);+ tally.call();+ }+ self.draw(frame, pass, Phase::All, &tally);+ self.publish(tally.stats());+ }++ /// What the last frame drew; the handle stays current as later frames are drawn.+ pub fn stats(&self) -> DrawStatsHandle {+ self.stats.clone()+ }++ fn publish(&self, drawn: DrawStats) {+ if let Ok(mut s) = self.stats.lock() {+ *s = drawn;}- self.draw(frame, pass, Phase::All);}/// The target the pipelines draw into.@@ -2238,8 +2311,8 @@ impl Renderer {}impl Renderer {- /// Draw the frame's scenes into `pass` (its viewport already set).- fn draw(&self, cb: &Frame, pass: &mut wgpu::RenderPass<'static>, phase: Phase) {+ /// Draw the frame's scenes into `pass` (its viewport already set), counting what it draws.+ fn draw(&self, cb: &Frame, pass: &mut wgpu::RenderPass<'static>, phase: Phase, tally: &Tally) {let res = self;pass.set_bind_group(0, &res.bind, &[]);let tris = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline, b: &Option<Batch>| {@@ -2248,6 +2321,7 @@ impl Renderer {for (buffer, count) in &b.parts {pass.set_vertex_buffer(0, buffer.slice(..));pass.draw(0..*count, 0..1);+ tally.triangles(*count, 1);}}};@@ -2257,6 +2331,7 @@ impl Renderer {for (buffer, count) in &b.parts {pass.set_vertex_buffer(0, buffer.slice(..));pass.draw(0..6, 0..*count);+ tally.segments(*count);}}};@@ -2284,12 +2359,13 @@ impl Renderer {pass.set_vertex_buffer(1, d.colors.slice(..));pass.set_index_buffer(d.mesh.indices.slice(..), wgpu::IndexFormat::Uint32);pass.draw_indexed(0..d.mesh.index_count, 0, 0..1);+ tally.triangles(d.mesh.index_count, 1);}};// Instanced meshes, with the pipeline for smooth and for flat triangles.let instanced = |pass: &mut wgpu::RenderPass<'static>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline| {for d in m.instanced.iter().filter(|d| d.look == InstanceLook::Opaque) {- d.draw(pass, smooth, flat);+ d.draw(pass, smooth, flat, tally);}};// Whole highlighted bodies: the model's own evaluated plan triangles, drawn again in a@@ -2321,6 +2397,7 @@ impl Renderer {if lo < hi {pass.set_vertex_buffer(0, buffer.slice(..));pass.draw(lo - base..hi - base, 0..1);+ tally.triangles(hi - lo, 1);}base = end;}@@ -2331,7 +2408,7 @@ impl Renderer {let tinted_instanced =|pass: &mut wgpu::RenderPass<'static>, smooth: &wgpu::RenderPipeline, flat: &wgpu::RenderPipeline, list: &[InstancedDraw]| {for d in list.iter().filter(|d| d.look == InstanceLook::Opaque) {- d.draw(pass, smooth, flat);+ d.draw(pass, smooth, flat, tally);}};let sectioned = cb.clip[..3].iter().map(|c| c * c).sum::<f32>() > 0.25;@@ -2384,6 +2461,7 @@ impl Renderer {for (buffer, count) in &q.parts {pass.set_vertex_buffer(0, buffer.slice(..));pass.draw(0..*count, 0..1);+ tally.triangles(*count, 1);}}}@@ -2396,7 +2474,7 @@ impl Renderer {let see_through =|pass: &mut wgpu::RenderPass<'static>, look: InstanceLook, (smooth, flat): &(wgpu::RenderPipeline, wgpu::RenderPipeline)| {for d in m.instanced.iter().filter(|d| d.look == look) {- d.draw(pass, smooth, flat);+ d.draw(pass, smooth, flat, tally);}};tris(pass, &res.glass_far, &m.glass);@@ -2431,7 +2509,7 @@ impl Renderer {}/// The model's see-through surfaces into the order-independent transparency's targets.- fn draw_see_through(&self, pass: &mut wgpu::RenderPass<'static>, p: &oit::Pipelines) {+ fn draw_see_through(&self, pass: &mut wgpu::RenderPass<'static>, p: &oit::Pipelines, tally: &Tally) {let m = &self.model;pass.set_bind_group(0, &self.bind, &[]);pass.set_pipeline(&p.built);@@ -2439,10 +2517,11 @@ impl Renderer {for (buffer, count) in &batch.parts {pass.set_vertex_buffer(0, buffer.slice(..));pass.draw(0..*count, 0..1);+ tally.triangles(*count, 1);}}for d in m.instanced.iter().filter(|d| d.look != InstanceLook::Opaque) {- d.draw(pass, &p.instanced, &p.instanced_flat);+ d.draw(pass, &p.instanced, &p.instanced_flat, tally);}}}@@ -2555,22 +2634,29 @@ impl Renderer {}).forget_lifetime()};+ let tally = Tally::default();let (Some(p), Some(t), true) = (&self.oit, &self.oit_targets, see_through) else {let mut first = pass(encoder, true);first.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0);- self.draw(cb, &mut first, Phase::All);+ self.draw(cb, &mut first, Phase::All, &tally);+ drop(first);+ self.ss_stats = tally.stats();return true;};{let mut first = pass(encoder, true);first.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0);- self.draw(cb, &mut first, Phase::BeforeSeeThrough);+ self.draw(cb, &mut first, Phase::BeforeSeeThrough, &tally);}- p.accumulate(encoder, t, ss.depth.as_ref(), stencil, |pass| self.draw_see_through(pass, p));+ p.accumulate(encoder, t, ss.depth.as_ref(), stencil, |pass| self.draw_see_through(pass, p, &tally));p.composite(encoder, t, &ss.color, ss.resolve.as_ref());- let mut over = pass(encoder, false);- over.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0);- self.draw(cb, &mut over, Phase::AfterSeeThrough);+ tally.call();+ {+ let mut over = pass(encoder, false);+ over.set_viewport(0.0, 0.0, size[0] as f32, size[1] as f32, 0.0, 1.0);+ self.draw(cb, &mut over, Phase::AfterSeeThrough, &tally);+ }+ self.ss_stats = tally.stats();true}diff --git a/crates/gpu/src/view/ao.rs b/crates/gpu/src/view/ao.rsindex 8844671059..7bba01b88b 100644--- a/crates/gpu/src/view/ao.rs+++ b/crates/gpu/src/view/ao.rs@@ -168,8 +168,10 @@ impl Resources {pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32);pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1);}+ // The depth prepass is left out of the performance overlay's counts, as before.+ let uncounted = super::Tally::default();for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) {- draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline);+ draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline, &uncounted);}}}diff --git a/crates/gpu/tests/capture.rs b/crates/gpu/tests/capture.rsindex 218bdfb8ef..9f7258e2f7 100644--- a/crates/gpu/tests/capture.rs+++ b/crates/gpu/tests/capture.rs@@ -96,6 +96,31 @@ fn pictures_show_appearances() {assert!(pixels(&img).all(|p| p[3] == 255), "the picture is opaque");}+/// The renderer counts what it draws (the performance overlay, #2548): every mesh triangle and+/// edge segment of the scene, more with more geometry, nothing with nothing to draw.+#[test]+fn the_renderer_counts_what_it_draws() {+ let Some(c) = capturer() else { return };+ let drawn = |s: &Session| {+ let cam = view::home_camera(s);+ let scene = view::scene_with_guides(s, &cam, None, Guides { grid: false, axes: false });+ let triangles: usize = scene.meshes.iter().map(|m| m.mesh.triangles.len()).sum();+ c.rgba(&scene, &cam, 160, 100).unwrap();+ (c.last_stats(), triangles as u64)+ };+ let (empty, _) = drawn(&Session::default());+ assert_eq!((empty.triangles, empty.line_segments), (0, 0), "{empty:?}");+ let (one, one_mesh) = drawn(&session(&[("solid.box", json!({"length": 40, "width": 30, "height": 20}))]));+ assert!(one_mesh >= 12 && one.triangles >= one_mesh, "{one:?} for {one_mesh} mesh triangles");+ assert!(one.line_segments >= 12 && one.draw_calls > empty.draw_calls, "{one:?}");+ let (two, two_mesh) = drawn(&session(&[+ ("solid.box", json!({"length": 40, "width": 30, "height": 20})),+ ("solid.cylinder", json!({"diameter": 14, "height": 30, "base": [50, 15, 0], "operation": "new"})),+ ]));+ assert!(two_mesh > one_mesh && two.triangles >= two_mesh && two.triangles > one.triangles, "{two:?} for {two_mesh}");+ assert!(two.line_segments > one.line_segments, "{two:?}");+}+/// The ground grid and the origin's axes each change the picture.#[test]fn guides_change_the_picture() {diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex e94cba31b7..7dad4493bd 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -342,6 +342,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->"hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")),"renderer": if app.viewport.gpu.is_some() { "gpu" } else { "cpu" },"frame_ms": app.frame_ms,+ "draw": app.viewport.draw_stats.as_ref().and_then(|s| s.lock().ok().map(|d| json!({+ "draw_calls": d.draw_calls, "triangles": d.triangles, "line_segments": d.line_segments, "supersampled": d.supersampled,+ }))),+ "adapter": app.viewport.adapter,"file_busy": app.file_load.busy(),"file_picker_busy": app.file_picker_busy(),"file_dialog_open": app.file_picker_busy(),diff --git a/crates/ui-egui/src/frame_rate.rs b/crates/ui-egui/src/frame_rate.rsindex 6904539f0e..c3507ef37d 100644--- a/crates/ui-egui/src/frame_rate.rs+++ b/crates/ui-egui/src/frame_rate.rs@@ -1,8 +1,13 @@-//! The viewport's frame-rate readout (Preferences ▸ Graphics ▸ "Frame rate").+//! The viewport's frame-rate readout (Preferences ▸ Graphics ▸ "Frame rate") and its details+//! (#2548): a graph of the last frames' times with the triangles drawn over it, a histogram of+//! frame times, and what the GPU drew. Click the readout to show or hide the details.-use egui::{FontId, Rect, pos2, vec2};+use std::collections::VecDeque;++use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, pos2, vec2};use crate::SolveApp;+use crate::i18n::tr;use crate::theme::Tokens;/// Weight of the newest frame in the running mean (roughly the last 20 frames count).@@ -12,28 +17,64 @@ const NEWEST: f64 = 0.05;/// so nothing was drawn.const IDLE_AFTER: f64 = 1.0;-/// Frames per second, averaged over recent frames.-#[derive(Clone, Copy, Debug, Default)]+/// Frames the graph and the histogram keep: about four seconds at 60 frames per second.+pub const HISTORY: usize = 240;++/// The histogram's buckets: frames up to each time (ms); the last takes everything slower.+/// 17 and 34 ms hold the 60 and 30 FPS frames with a display's usual jitter.+pub const BUCKETS: [f32; 9] = [4.0, 8.0, 12.0, 17.0, 25.0, 34.0, 50.0, 100.0, f32::INFINITY];++/// One frame of the history.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Sample {+ /// Time since the previous frame (ms).+ pub ms: f32,+ /// What the GPU drew in it.+ pub triangles: u64,+ /// The model's scene was rebuilt for it (the design or what is shown changed).+ pub rebuilt: bool,+}++/// Frames per second, averaged over recent frames, and the last frames for the details.+#[derive(Clone, Debug, Default)]pub struct FrameRate {mean_dt: f64,/// The last gap between frames was a pause: the view is idle.idle: bool,+ samples: VecDeque<Sample>,+ /// The model scene's key at the last frame, to mark the frames that rebuilt it.+ scene_key: u64,}impl FrameRate {/// Takes the time since the previous frame, in seconds. A gap over a second means the view/// was idle (it draws only when something changes): the mean starts again from the next- /// frames. Anything that isn't a positive finite time is left out.- pub fn record(&mut self, dt: f64) {+ /// frames, and the history keeps the frames before the pause. Anything that isn't a positive+ /// finite time is left out. `true` when it counted as a frame.+ pub fn record(&mut self, dt: f64) -> bool {if !dt.is_finite() || dt <= 0.0 {- return;+ return false;}if dt > IDLE_AFTER {- *self = FrameRate { mean_dt: 0.0, idle: true };- return;+ (self.mean_dt, self.idle) = (0.0, true);+ return false;}self.mean_dt = if self.mean_dt > 0.0 { self.mean_dt + NEWEST * (dt - self.mean_dt) } else { dt };self.idle = false;+ true+ }++ /// Adds a frame to the history, dropping the oldest past [`HISTORY`].+ pub fn push(&mut self, sample: Sample) {+ if self.samples.len() >= HISTORY {+ self.samples.pop_front();+ }+ self.samples.push_back(sample);+ }++ /// The last frames, oldest first.+ pub fn samples(&self) -> impl ExactSizeIterator<Item = &Sample> {+ self.samples.iter()}/// The averaged rate; `None` before the first frame was recorded and while the view is idle.@@ -48,35 +89,216 @@ impl FrameRate {}self.fps().map(|fps| format!("{fps:.0} FPS · {:.1} ms", 1000.0 * self.mean_dt))}++ /// The mean time (ms) of the slowest 1% of the history's frames (at least one), and the+ /// slowest frame; `None` without a history.+ pub fn slowest(&self) -> Option<(f32, f32)> {+ let mut ms: Vec<f32> = self.samples.iter().map(|s| s.ms).collect();+ ms.sort_by(|a, b| b.total_cmp(a));+ let worst = *ms.first()?;+ let n = (ms.len() / 100).max(1);+ Some((ms.iter().take(n).sum::<f32>() / n as f32, worst))+ }++ /// How many of the history's frames fall in each of [`BUCKETS`].+ pub fn histogram(&self) -> [u32; BUCKETS.len()] {+ let mut counts = [0; BUCKETS.len()];+ for s in &self.samples {+ let i = BUCKETS.iter().position(|&up_to| s.ms <= up_to).unwrap_or(BUCKETS.len() - 1);+ if let Some(c) = counts.get_mut(i) {+ *c += 1;+ }+ }+ counts+ }}-/// Records this frame and paints the readout in the view's bottom-right corner. The readout asks-/// for no frames of its own, so it shows how often the view is really drawn and leaves an idle-/// window idle (a readout that redrew every frame kept the GPU busy on an untouched window). Once-/// the frames stop, one more frame a little over [`IDLE_AFTER`] later shows the view idle.-pub(crate) fn paint(app: &mut SolveApp, ctx: &egui::Context, painter: &egui::Painter, rect: Rect) {+/// `1234567` as `1 234 567`: counts read at a glance.+fn grouped(n: u64) -> String {+ let digits = n.to_string();+ let mut out = String::with_capacity(digits.len() + digits.len() / 3);+ for (i, c) in digits.chars().enumerate() {+ if i > 0 && (digits.len() - i).is_multiple_of(3) {+ out.push('\u{2009}');+ }+ out.push(c);+ }+ out+}++/// A frame time's colour: within 60 FPS, within 30 FPS, slower (with the buckets' allowance for+/// jitter).+fn budget_colour(t: &Tokens, ms: f32) -> Color32 {+ if ms <= 17.0 {+ t.accent+ } else if ms <= 34.0 {+ t.warning+ } else {+ t.error+ }+}++/// Records this frame and paints the readout in the view's bottom-right corner, with the details+/// above it when they are on. The readout asks for no frames of its own, so it shows how often the+/// view is really drawn and leaves an idle window idle (a readout that redrew every frame kept the+/// GPU busy on an untouched window); the details show the frames the view drew. Once the frames+/// stop, one more frame a little over [`IDLE_AFTER`] later shows the view idle.+pub(crate) fn paint(app: &mut SolveApp, ui: &egui::Ui, painter: &egui::Painter, rect: Rect) {if !app.preferences.show_frame_rate {app.frame_rate = FrameRate::default();return;}- app.frame_rate.record(f64::from(ctx.input(|i| i.unstable_dt)));+ let ctx = ui.ctx();+ let drawn = app.viewport.draw_stats.as_ref().and_then(|s| s.lock().ok().map(|s| *s)).unwrap_or_default();+ if app.frame_rate.record(f64::from(ctx.input(|i| i.unstable_dt))) {+ let ms = ctx.input(|i| i.unstable_dt) * 1000.0;+ let rebuilt = app.frame_rate.scene_key != app.viewport.key;+ app.frame_rate.push(Sample { ms, triangles: drawn.triangles, rebuilt });+ }+ app.frame_rate.scene_key = app.viewport.key;if app.frame_rate.fps().is_some() {ctx.request_repaint_after(std::time::Duration::from_secs_f64(IDLE_AFTER + 0.1));}let Some(text) = app.frame_rate.label() else { return };let t = Tokens::get();- let font = FontId::monospace(crate::theme::Tokens::get().font_body);- let galley = painter.layout_no_wrap(text, font, t.text);+ let font = FontId::monospace(t.font_body);+ let galley = painter.layout_no_wrap(text, font.clone(), t.text);let size = galley.size() + vec2(16.0, 8.0);- let r = Rect::from_min_size(pos2(rect.right() - 12.0 - size.x, rect.bottom() - 12.0 - size.y), size);+ let mut r = Rect::from_min_size(pos2(rect.right() - 12.0 - size.x, rect.bottom() - 12.0 - size.y), size);+ // Above the navigation bar where a narrow view brings the two together.+ if let Some(nav) = app.viewport.layout.as_ref().map(|l| l.navigation)+ && r.intersects(nav.expand(4.0))+ {+ r = r.translate(vec2(0.0, nav.top() - 6.0 - r.bottom()));+ }+ let id = egui::Id::new("sc_frame_rate");+ let clicked = ui.interact(r, id, Sense::click()).on_hover_text(tr("perf.click_for_details")).clicked();+ if clicked {+ app.preferences.frame_rate_details = !app.preferences.frame_rate_details;+ }painter.rect(r, t.radius_sm, t.overlay, t.control_border_stroke(t.border), egui::StrokeKind::Inside);crate::scenario::publish_target("viewport:frame_rate", r);painter.galley(r.center() - galley.size() / 2.0, galley, t.text);+ if app.preferences.frame_rate_details {+ details(app, painter, rect, r, drawn, &font);+ }+}++/// The details above the readout `below`: the frame-time graph with the triangles over it, the+/// histogram and what the GPU drew.+fn details(app: &SolveApp, painter: &egui::Painter, view: Rect, below: Rect, drawn: crate::gpu::DrawStats, font: &FontId) {+ let t = Tokens::get();+ let (pad, row, label_h, graph_h, hist_h) = (8.0, 16.0, 12.0, 56.0, 40.0);+ let lines = 7.0 + 0.8; // seven rows and the adapter's name+ let w = 300.0_f32.min(view.width() - 24.0);+ let h = pad * 2.0 + row + label_h + graph_h + 6.0 + hist_h + row + lines * row;+ if w < 160.0 || h > view.height() - below.height() - 30.0 {+ return;+ }+ let panel = Rect::from_min_size(pos2(view.right() - 12.0 - w, below.top() - 6.0 - h), vec2(w, h));+ painter.rect(panel, t.radius_sm, t.dialog_bg, t.control_border_stroke(t.border), egui::StrokeKind::Inside);+ crate::scenario::publish_handle("viewport:frame_details", panel.center());+ let inner = panel.shrink(pad);+ let small = FontId::monospace(t.font_small);+ let text = |pos: egui::Pos2, align: Align2, s: &str, font: &FontId, c: Color32| {+ painter.text(pos, align, s, font.clone(), c);+ };+ let mut y = inner.top();++ // Heading: the slowest frames, which the mean hides.+ let heading = match app.frame_rate.slowest() {+ Some((low, worst)) => format!("{} {:.0} FPS · {} {worst:.1} ms", tr("perf.low_1"), 1000.0 / low.max(0.01), tr("perf.worst")),+ None => String::new(),+ };+ text(pos2(inner.left(), y), Align2::LEFT_TOP, &heading, font, t.text);+ y += row;++ // The frame-time graph: one bar per frame, newest on the right, the 60 and 30 FPS budgets as+ // dashed lines, the triangles drawn as a solid line over it and frames that rebuilt the scene+ // marked with a tick.+ let graph = Rect::from_min_size(pos2(inner.left(), y + label_h), vec2(inner.width(), graph_h));+ let samples: Vec<Sample> = app.frame_rate.samples().copied().collect();+ let top_ms = samples.iter().map(|s| s.ms).fold(33.3_f32 * 1.25, f32::max).min(250.0);+ let y_of = |ms: f32| graph.bottom() - graph.height() * (ms / top_ms).clamp(0.0, 1.0);+ let bar = graph.width() / HISTORY as f32;+ let first = HISTORY.saturating_sub(samples.len()) as f32;+ for (i, s) in samples.iter().enumerate() {+ let x = graph.left() + (first + i as f32) * bar;+ let r = Rect::from_min_max(pos2(x, y_of(s.ms)), pos2(x + bar.max(1.0), graph.bottom()));+ painter.rect_filled(r, 0.0, budget_colour(&t, s.ms));+ if s.rebuilt {+ painter.line_segment([pos2(x, graph.top()), pos2(x, graph.top() + 5.0)], Stroke::new(1.0, t.text));+ }+ }+ for (ms, label) in [(16.7, "60 FPS"), (33.3, "30 FPS")] {+ let gy = y_of(ms);+ painter.extend(egui::Shape::dashed_line(&[pos2(graph.left(), gy), pos2(graph.right(), gy)], Stroke::new(1.0, t.text_dim), 3.0, 3.0));+ text(pos2(graph.left() + 2.0, gy - 1.0), Align2::LEFT_BOTTOM, label, &small, t.text_dim);+ }+ let most = samples.iter().map(|s| s.triangles).max().unwrap_or(0);+ if most > 0 {+ let pts: Vec<egui::Pos2> = samples+ .iter()+ .enumerate()+ .map(|(i, s)| {+ pos2(graph.left() + (first + i as f32 + 0.5) * bar, graph.bottom() - graph.height() * 0.75 * (s.triangles as f32 / most as f32))+ })+ .collect();+ painter.add(egui::Shape::line(pts, Stroke::new(1.5, t.text.gamma_multiply(0.8))));+ text(pos2(graph.left(), graph.top() - 1.0), Align2::LEFT_BOTTOM, &format!("— {} {}", grouped(most), tr("perf.triangles")), &small, t.text);+ }+ text(pos2(graph.right(), graph.top() - 1.0), Align2::RIGHT_BOTTOM, &format!("↑ {top_ms:.0} ms"), &small, t.text_dim);+ y = graph.bottom() + 6.0;++ // The histogram: how many frames took each span of time.+ let counts = app.frame_rate.histogram();+ let total = counts.iter().sum::<u32>().max(1) as f32;+ let cell = inner.width() / BUCKETS.len() as f32;+ let hist = Rect::from_min_size(pos2(inner.left(), y), vec2(inner.width(), hist_h));+ let mut from = 0.0_f32;+ for (i, (&n, &up_to)) in counts.iter().zip(&BUCKETS).enumerate() {+ let x = hist.left() + i as f32 * cell;+ let share = n as f32 / total;+ let top = hist.bottom() - hist.height() * share;+ let colour = budget_colour(&t, if up_to.is_finite() { up_to } else { from + 1.0 });+ painter.rect_filled(Rect::from_min_max(pos2(x + 1.0, top), pos2(x + cell - 1.0, hist.bottom())), 1.0, colour);+ if n > 0 {+ let pct = if share < 0.01 { "<1%".to_string() } else { format!("{:.0}%", share * 100.0) };+ text(pos2(x + cell / 2.0, top - 1.0), Align2::CENTER_BOTTOM, &pct, &small, t.text_dim);+ }+ let label = if up_to.is_finite() { format!("{up_to:.0}") } else { format!("{from:.0}+") };+ text(pos2(x + cell / 2.0, hist.bottom() + 1.0), Align2::CENTER_TOP, &label, &small, t.text_dim);+ from = up_to;+ }+ y = hist.bottom() + row;++ // What the GPU drew last frame, and the work around it.+ let mut kv = |k: &str, v: String| {+ text(pos2(inner.left(), y), Align2::LEFT_TOP, k, font, t.text_dim);+ text(pos2(inner.right(), y), Align2::RIGHT_TOP, &v, font, t.text);+ y += row;+ };+ kv(tr("perf.triangles"), grouped(drawn.triangles));+ kv(tr("perf.line_segments"), grouped(drawn.line_segments));+ kv(tr("perf.draw_calls"), grouped(u64::from(drawn.draw_calls)));+ let px = view.size() * painter.ctx().pixels_per_point();+ let msaa = app.viewport.gpu.map_or(1, |g| g.samples);+ let ss = if drawn.supersampled { " · SSAA" } else { "" };+ kv(tr("perf.viewport"), format!("{:.0}×{:.0} · MSAA {msaa}×{ss}", px.x, px.y));+ kv(tr("perf.ui_time"), format!("{:.1} ms", app.frame_ms));+ kv(tr("perf.scene_build"), format!("{:.1} ms", app.viewport.build_ms));+ // The adapter's name can be long: on a line of its own, cut to the panel's width.+ let (backend, adapter) = app.viewport.adapter.split_once(" · ").unwrap_or(("CPU", ""));+ kv(tr("perf.renderer"), backend.to_string());+ let room = (inner.width() / 6.0) as usize;+ let adapter: String =+ if adapter.chars().count() > room { adapter.chars().take(room.saturating_sub(1)).chain(['…']).collect() } else { adapter.to_string() };+ text(pos2(inner.right(), y - 2.0), Align2::RIGHT_TOP, &adapter, &small, t.text_dim);}#[cfg(test)]mod tests {- use super::FrameRate;+ use super::{BUCKETS, FrameRate, HISTORY, Sample, grouped};#[test]fn steady_frames_read_their_rate() {@@ -93,14 +315,14 @@ mod tests {fn hostile_times_are_left_out_and_a_pause_reads_idle() {let mut f = FrameRate::default();for dt in [0.0, -1.0, f64::NAN, f64::INFINITY] {- f.record(dt);+ assert!(!f.record(dt));}assert_eq!(f.fps(), None);assert_eq!(f.label(), None);- f.record(0.01);+ assert!(f.record(0.01));assert!((f.fps().unwrap_or(0.0) - 100.0).abs() < 1e-6);// Nothing drawn for 3 s: the view was idle, and the next frames start a new mean.- f.record(3.0);+ assert!(!f.record(3.0));assert_eq!(f.fps(), None);assert_eq!(f.label().as_deref(), Some("0 FPS"));f.record(1.0 / 60.0);@@ -119,7 +341,7 @@ mod tests {let mut out = ctx.run_ui(raw, |ui| {let rect = ui.max_rect();let painter = ui.painter().clone();- super::paint(&mut app, ui.ctx(), &painter, rect);+ super::paint(&mut app, ui, &painter, rect);});out.textures_delta.clear();out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.repaint_delay)@@ -143,4 +365,60 @@ mod tests {}assert!((f.fps().unwrap_or(0.0) - 30.0).abs() < 0.1);}++ /// The details keep the last [`HISTORY`] frames, and the slowest 1% and the histogram show a+ /// stutter that the mean hides (#2548).+ #[test]+ fn the_history_shows_stutters_the_mean_hides() {+ let mut f = FrameRate::default();+ assert_eq!(f.slowest(), None);+ assert_eq!(f.histogram(), [0; BUCKETS.len()]);+ for i in 0..1000 {+ let ms = if i % 100 == 0 { 120.0 } else { 10.0 };+ f.record(f64::from(ms) / 1000.0);+ f.push(Sample { ms, triangles: i, rebuilt: false });+ }+ assert_eq!(f.samples().len(), HISTORY);+ assert_eq!(f.samples().last().map(|s| s.triangles), Some(999), "the newest frame is last");+ assert!(f.fps().unwrap_or(0.0) > 50.0, "the mean barely moves");+ let (low, worst) = f.slowest().unwrap_or_default();+ assert_eq!((low, worst), (120.0, 120.0), "the stutters are the slowest 1%");+ let h = f.histogram();+ assert_eq!(h.iter().sum::<u32>(), HISTORY as u32);+ assert_eq!((h[2], h[8]), (HISTORY as u32 - 2, 2), "10 ms frames up to 12 ms, two stutters over 100 ms");+ assert_eq!(BUCKETS.last(), Some(&f32::INFINITY), "the last bucket takes every slower frame");+ }++ /// Clicking the readout shows the details and clicking it again hides them; the choice is a+ /// preference, and `ui.inspect` carries what the GPU drew.+ #[test]+ fn clicking_the_readout_shows_and_hides_the_details() {+ use crate::scenario::handle_at;+ use serde_json::json;+ let mut h = crate::scenario::Harness::new();+ h.call("ui.prefs", json!({"show_frame_rate": true}));+ h.frames(4);+ let readout = handle_at("viewport:frame_rate").expect("the readout is drawn");+ assert!(handle_at("viewport:frame_details").is_none());+ h.call("ui.click", json!({"x": readout.x, "y": readout.y}));+ h.frames(2);+ assert!(h.app.preferences.frame_rate_details);+ assert!(handle_at("viewport:frame_details").is_some(), "the details are drawn");+ assert!(h.app.frame_rate.samples().len() >= 2, "frames are kept for the graph");+ let inspect = h.call("ui.inspect", json!({}));+ assert!(inspect["result"].get("draw").is_some() && inspect["result"].get("adapter").is_some(), "{inspect}");+ let readout = handle_at("viewport:frame_rate").expect("the readout is still drawn");+ h.call("ui.click", json!({"x": readout.x, "y": readout.y}));+ h.frames(2);+ assert!(!h.app.preferences.frame_rate_details);+ assert!(handle_at("viewport:frame_details").is_none());+ }++ #[test]+ fn counts_are_grouped_by_thousands() {+ assert_eq!(grouped(0), "0");+ assert_eq!(grouped(999), "999");+ assert_eq!(grouped(1000), "1\u{2009}000");+ assert_eq!(grouped(12_345_678), "12\u{2009}345\u{2009}678");+ }}diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rsindex ea692167ba..f95817f8ea 100644--- a/crates/ui-egui/src/gpu.rs+++ b/crates/ui-egui/src/gpu.rs@@ -8,8 +8,9 @@ use std::sync::{Arc, Mutex};use egui_wgpu::wgpu;pub use solidcraft_gpu::view::{- AccessMap, BlockBytes, BlockTris, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook, InstancedMesh, LINE_SIZE, LOD_PX, PBR_SIZE,- PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot, SharedTris, TRI_SIZE, level_for, placement_scale, supersampled_size,+ AccessMap, BlockBytes, BlockTris, DrawStats, DrawStatsHandle, Frame, GpuImage, GpuScene, GpuTarget, INSTANCE_SIZE, InstanceLook, InstancedMesh,+ LINE_SIZE, LOD_PX, PBR_SIZE, PlannedBody, Renderer, SHARED_SIZE, SceneBlock, SceneSlot, SharedTris, TRI_SIZE, level_for, placement_scale,+ supersampled_size,};/// A frame of the viewport as an egui paint callback.@@ -19,13 +20,15 @@ pub struct ViewportCallback(pub Frame);/// MSAA settings, and the target of the pass the picture is shown in. Without a stencil the/// section cap does not hide the inside of cut bodies. Without `gpu_meshing` (safe mode) bodies/// are meshed on the CPU. When the two targets differ, the scene is drawn offscreen and blitted.-pub fn install(rs: &egui_wgpu::RenderState, scene: GpuTarget, window: GpuTarget, gpu_meshing: bool) -> GpuTarget {+/// Also returns the handle to what each frame drew.+pub fn install(rs: &egui_wgpu::RenderState, scene: GpuTarget, window: GpuTarget, gpu_meshing: bool) -> (GpuTarget, DrawStatsHandle) {let tess = if gpu_meshing { solidcraft_gpu::view::tessellation(&rs.adapter, &rs.device, &rs.queue, solidcraft_gpu::SHADER) } else { None };let scene = GpuTarget { tess: tess.is_some(), ..scene };let window = GpuTarget { tess: tess.is_some(), ..window };let res = Renderer::with_window_target(&rs.device, scene, window, tess);+ let stats = res.stats();rs.renderer.write().callback_resources.insert(res);- scene+ (scene, stats)}/// Draw this process's headless pictures (`ui.render`, the agent's view image, thumbnails ofdiff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d8841628b0..ff4429f5b2 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -676,7 +676,9 @@ impl SolveApp {}fn set_wgpu_targets(&mut self, rs: &egui_wgpu::RenderState, scene: crate::gpu::GpuTarget, window: crate::gpu::GpuTarget) {- self.viewport.gpu = Some(gpu::install(rs, scene, window, !self.cpu_meshing));+ let (target, stats) = gpu::install(rs, scene, window, !self.cpu_meshing);+ self.viewport.gpu = Some(target);+ self.viewport.draw_stats = Some(stats);render_workspace::invalidate_scene(self);let (samples, has_depth) = self.viewport.gpu.map_or((1, false), |g| (g.samples.max(1), g.depth.is_some()));self.render_workspace.host = match render_workspace::host_executor(rs.device.limits().max_texture_dimension_2d, has_depth, samples) {@@ -696,6 +698,7 @@ impl SolveApp {self.msaa_supported = rs.msaa_supported.clone();let info = rs.adapter.get_info();self.help.gpu = Some(format!("{} ({:?}, {:?})", info.name.trim(), info.backend, info.device_type));+ self.viewport.adapter = format!("{:?} · {}", info.backend, info.name);}/// Preferences kept between runs (JSON), for the host to store.diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex 2048ce72d3..06aaa1ef03 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -531,6 +531,8 @@ preference_settings! {supersampling_adaptive: bool = true, PAGE_GRAPHICS => check_tr("ui.supersampling_adaptive");/// Show the frame rate in the view's corner (the view then redraws every frame).show_frame_rate: bool = false, PAGE_GRAPHICS => check_id("ui.frame_rate");+ /// With the frame rate: a frame-time graph, a histogram and what the GPU drew (#2548).+ frame_rate_details: bool = false, PAGE_GRAPHICS;/// Show world X/Y/Z component dimensions beside the total distance in Measure.measure_axis_distances: bool = true, PAGE_GRAPHICS => check_id("settings.measure_axis_distances");/// Decimals shown for lengths and angles.diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rsindex 869a52599c..9534485dc5 100644--- a/crates/ui-egui/src/prefs/graphics.rs+++ b/crates/ui-egui/src/prefs/graphics.rs@@ -123,6 +123,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {ui_kit::checkbox(left, crate::i18n::tr_label("Grid"), &mut app.ui.show_grid);ui_kit::checkbox(left, crate::i18n::tr_label("Perspective view"), &mut app.ui.perspective);setting::show_frame_rate(app, left).on_hover_text(app.tr("settings.frame_rate_note"));+ left.add_enabled_ui(app.preferences.show_frame_rate, |ui| {+ ui_kit::checkbox(ui, app.tr("ui.frame_rate_details"), &mut app.preferences.frame_rate_details)+ .on_hover_text(app.tr("settings.frame_rate_details_note"));+ });setting::reference_geometry_through_bodies(app, left).on_hover_text(app.tr("settings.reference_geometry_through_bodies_help"));}if let Some(right) = columns.get_mut(1) {diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex b2183e89f2..cc830df04c 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -93,8 +93,12 @@ pub struct ViewportState {pub(crate) palette_rect: Option<Rect>,pub(crate) dialog_rect: Option<Rect>,pub gpu: Option<GpuTarget>,+ /// What the GPU drew last frame, shared with the renderer (the frame-rate details, #2548).+ pub(crate) draw_stats: Option<crate::gpu::DrawStatsHandle>,+ /// The graphics backend and adapter, as the frame-rate details show them.+ pub(crate) adapter: String,slot: SceneSlot,- key: u64,+ pub(crate) key: u64,sketch_slot: SceneSlot,sketch_key: u64,physical_scale: f32,@@ -3145,7 +3149,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {}let overlay_rect = crate::shell::bottom_overlay_rect(app, rect);analysis_legend(app, &painter, overlay_rect);- crate::frame_rate::paint(app, ui.ctx(), &painter, overlay_rect);+ crate::frame_rate::paint(app, ui, &painter, overlay_rect);// ---- interaction ----// A tool's click that moved on the way (#2448) clicks where the button is let go.diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.mdindex 08bcb9967c..4b065d59dc 100644--- a/docs/book/src/guide/ui-tour.md+++ b/docs/book/src/guide/ui-tour.md@@ -184,6 +184,21 @@ Command icons use the shared SVG palette.Imported themes are kept with your preferences, so they work in the browser app too. Colourvision modes still apply on top of any theme.+Graphics › **Frame rate** shows frames per second in the view's bottom-right corner. Click it,+or turn on **Frame rate details**, for the performance overlay:++- a graph of the last few seconds of frames, one bar per frame, with lines at 60 and 30 frames+ per second. The triangles drawn are a line over it, and a tick at the top marks each frame that+ rebuilt the scene, so you can see how geometry changes the frame time;+- a histogram of frame times, the 1% low (the mean of the slowest 1% of frames) and the worst+ frame, which show stutters that an average hides;+- what the GPU drew last frame (triangles, line segments, draw calls), the viewport's size in+ pixels with its MSAA and supersampling, the time the interface took, the last scene build and+ the graphics backend and adapter.++While the readout is on, the view redraws every frame. With vertical sync the frame rate tops+out at the display's refresh rate; the interface time and the GPU counts still show the work.+Navigation › **Smooth wheel zoom** is on by default. Turn it off to apply each wheel ortrackpad event immediately, with no smoothing tail. It is independent of **Animate viewchanges**, which controls axis views, Look At, Home and Fit. Re-enabling smoothing duringdiff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 9872188847..4773f65e6f 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -211,7 +211,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.| Method | Params | Notes ||---|---|---|-| `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, active tool/dialog, the status line (`status`: text and whether it is an error), hover, renderer, timings, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) |+| `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, active tool/dialog, the status line (`status`: text and whether it is an error), hover, renderer, timings, what the GPU drew last frame (`draw`: `draw_calls`, `triangles`, `line_segments`, `supersampled`; null without a GPU) and the graphics `adapter`, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) || `ui.set` | any `UiState` field (`tab`, `perspective`, `showGrid`, `dark`, `layout`, …), and the browser's view of the design, saved with it: `showOrigin` (the Origin folder's eye), `showSketches` (the design's Sketches folder, `c0/sketches` in `hiddenFolders`), `hiddenBodies`, `hiddenOrigin`, `hiddenSketches`, `shownSketches`, `hiddenJoints`, `hiddenFolders`, `hiddenProfiles`, `shownDims`, `lockedBodies` (whole lists; `browser.visibility` changes single items) | `dark: false` switches to the light theme; `layout: "floating"` (default) or `"compact"` (`"docked"` is also accepted) selects the transient shell layout without saving a preference. Scenarios use `{"call":"ui.set","params":{"layout":"docked"}}` || `ui.view` | `view`: `front`, `back`, `top`, `bottom`, `left`, `right`, `iso`, `home`, `fit`; `animate` (bool, default false: snap) | || `ui.camera` | `target?`: `[x, y, z]` (mm), `yaw?`, `pitch?`, `roll?` (radians), `distance?` (mm), `fov?`, `up?`; `fit?`: `true`, `false` or `[occurrence id or name…]` (`root`: the bodies outside every component) | the viewport's orbit camera: it looks at `target` from `distance` away; `yaw` 0 looks along +Y (from the front), `pitch` is the elevation (±π/2: straight down or up), `roll` turns the image. Fields given are set first (the others keep their values), then `fit` frames the listed occurrences (or everything), keeping the direction. The reply, passed back, sets the same view again, so a framing can be stored and replayed. `fov` and `up` follow the perspective setting (`ui.set`) and the up axis preference (`ui.prefs`) and can't change here; a refused field changes nothing |@@ -244,7 +244,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.| `ui.home` | `open?`: bool; `sample?`: index | the start page: show or hide it, open a built-in sample (once built); returns `open` and the recent designs || `ui.shortcut` | `command`, `key?`, `replace?` | a command's key, or rebinds it (`""` clears; a key another command uses is refused unless `replace`) || `ui.help` | `item?`: `about`, `shortcuts` (read only), `report` (opens a report draft for review), `crashes` (the Crash Reports window) | the version, commit, build date and diagnostic text |-| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` |+| `ui.prefs` | any of `default_units`, `nav` (`fusion`, `solidworks`, `inventor`, `alias`, `blender`, `tinkercad`, `openscad`, `touchpad`), `zoom_reverse`, `pan_reverse_x` (default false: horizontal scrolling pans the other way), `zoom_to_cursor`, `smooth_wheel_zoom` (default true), `trackpad_pan` (default true: two-finger scroll pans, except Touchpad always zooms; pinch zooms), `orbit_around` (`view_centre` (default: what Pan moves and Fit frames), `origin` (the world origin stays still on screen), `cursor` (the model point under the pointer when the drag began); the older `orbit_cursor` boolean still sets `cursor` when true), `look_at_anim`, `look_at_speed`, `middle_double_click` (`home` (default), `fit`, `off`), `msaa`, `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle), `window_system` (Linux: `auto` (default: XWayland whenever there is an X display, native Wayland on niri), `wayland`, `x11`; saved in `graphics.json`, applies at the next start; `SOLIDCRAFT_WAYLAND` overrides it), `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it), `length_decimals`, `angle_decimals`, `theme` (`dark`, `light`, `system` or a theme file's id: a built-in one such as `gruvbox-dark`, or an imported one; the reply's `theme_ids` lists them), `theme_import` (a `solidcraft-theme/1` file's JSON or text: adds the theme and turns it on; the reply's `theme_imported` is its id), `theme_remove` (an imported theme's id), `theme_export: true` (the reply's `theme_file` is the theme on now as a complete file; see [colour themes](book/src/guide/ui-tour.md#colour-themes)), `language` (`en`, `ja`, `de`, `fr`, `ko`, `ms`, `ru`, `uk`, `zh`; see [localization](localization.md)), `ui_scale`, `ui_font` (an installed font family or a font file for the interface; empty for the built-in font), `up_axis` (`z`, `y`), `offer_stand_up`, `extrude_auto_to_object` (default false: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object; it applies to Extrude dialogs opened afterwards), `hole_snaps` (default false: a Single hole snaps to its face's middle and round edges' centres), `hole_moves` (default false: a placed Single hole has a drag handle (`hole:<n>`), and a pick on a face that has a hole moves it there), `color_vision` (`off` (default), `protan`, `deutan`, `tritan`: colour vision modes, #778), `check_updates` (default true; [updates](book/src/guide/updates.md)); `open` (a page: General, Interface, Design, Navigation, Keyboard Shortcuts, Sketch, Graphics, AI, Plugins; Shortcuts, Assistant and Sketch & selection are aliases, and the former Selection page opens Sketch) opens the Preferences dialog there; `button`: `ok`, `cancel`, `apply`, `defaults`; `stand_up: true` stands up a just-opened Y-up file, `stand_up: false` leaves it as it is ("Leave it": the offer closes and `offer_stand_up` stays on); the offer's buttons are the handles `stand_up:stand`, `stand_up:leave` and `stand_up:never` | sets preferences (kept between runs), returns them all plus `dialog` (the open page or null), `dark` and `stand_up_offer` || `ui.capture` | `action?`: `capture`, `revert`, `cancel` | answers the Capture Position question (asked when a command starts or the design is saved while components were moved without capturing); without `action`, what waits || `ui.window` | `action`: minimize, maximize, restore, toggle, close | what the title bar's caption buttons do (on Windows and Linux the application bar is the title bar); close asks about unsaved designs first || `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it |