use std::marker::PhantomData; use std::ops::Deref; use std::ops::DerefMut; use egui::Ui; use egui::vec2; use wgpu::Buffer; use wgpu::BufferUsages; use wgpu::CommandEncoder; use wgpu::ComputePass; use wgpu::Device; use wgpu::QuerySet; use wgpu::Queue; macro_rules! begin_frame { ($encoder:ident) => { let mut $encoder = $encoder.begin_frame(None); }; ($encoder:ident, $name:literal) => { let mut $encoder = $encoder.begin_frame(Some($name)); }; } macro_rules! begin_scope { ($scope:ident, $name:literal) => { let mut $scope = $scope.begin_scope($name); }; } pub(crate) use begin_frame; pub(crate) use begin_scope; pub struct ScopeEncoder<'enc, 'prof_enc, T> { encoder: &'prof_enc mut ProfilingEncoder<'enc>, scope_index: usize, _phantom: PhantomData, } pub struct Scope { name: &'static str, start_index: QuerySetHandle, end_index: Option, children: Vec, } pub struct ProfilingEncoder<'enc> { device: Device, encoder: &'enc mut CommandEncoder, query_set_allocator: QuerySetAllocator, scopes: Vec, index_stack: Vec, // Stores a compute pass when currently in one compute_pass: Option<(usize, ComputePass<'static>)>, } pub struct GpuProfile { scopes: Vec, timestamps: Buffer, } pub struct Frame { pub name: &'static str, pub children: Vec, pub start_timestamp: u64, pub end_timestamp: u64, } #[derive(Default)] pub struct Profile { pub frames: Vec, } impl<'enc> ProfilingEncoder<'enc> { pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self { Self { encoder, query_set_allocator: QuerySetAllocator::new(device), scopes: Vec::new(), device: device.clone(), index_stack: Vec::new(), compute_pass: None, } } pub fn begin_frame<'prof_enc>( &'prof_enc mut self, frame_name: Option<&'static str>, ) -> ScopeEncoder<'enc, 'prof_enc, CommandEncoder> { let scope_index = self.begin_scope(None, frame_name.unwrap_or("Frame")); self.index_stack.push(scope_index); ScopeEncoder { encoder: self, scope_index, _phantom: Default::default(), } } fn begin_scope(&mut self, scope_index: Option, name: &'static str) -> usize { let begin_query = self.query_set_allocator.allocate(); if let Some((_, pass)) = &mut self.compute_pass { self.query_set_allocator .write_compute_timestamp(pass, &begin_query); } else { self.query_set_allocator .write_timestamp(self.encoder, &begin_query); } let scope = Scope { name, start_index: begin_query, end_index: None, children: Vec::new(), }; let new_scope_index = self.scopes.len(); self.scopes.push(scope); self.index_stack.push(new_scope_index); // Add this new stack to parent if let Some(scope_index) = scope_index { self.scopes[scope_index].children.push(new_scope_index); } new_scope_index } fn end_scope(&mut self, scope_index: usize) { let end_query = self.query_set_allocator.allocate(); if let Some((_, pass)) = &mut self.compute_pass { self.query_set_allocator .write_compute_timestamp(pass, &end_query); } else { self.query_set_allocator .write_timestamp(self.encoder, &end_query); } let scope = &mut self.scopes[scope_index]; let pop = self.index_stack.pop().unwrap(); assert_eq!( pop, scope_index, "Scopes must be defined in a stack fashion." ); scope.end_index = Some(end_query); } pub fn finish_profiler(self) -> GpuProfile { let timestamp_count = self.query_set_allocator.allocated_count(); let resolve_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("ProfilingEncoder::resolve_buffer"), size: size_of::() as u64 * timestamp_count as u64, usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC, mapped_at_creation: false, }); self.query_set_allocator .resolve_all(self.encoder, &resolve_buffer); GpuProfile { scopes: self.scopes, timestamps: resolve_buffer, } } } impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder> { pub fn begin_profiled_compute_pass<'scope>( &'scope mut self, label: &'static str, ) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>> { let new_scope = self.encoder.begin_scope(Some(self.scope_index), label); let compute_pass = self .encoder .begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(label), timestamp_writes: None, }) .forget_lifetime(); self.encoder.compute_pass = Some((new_scope, compute_pass)); ScopeEncoder { encoder: self.encoder, scope_index: new_scope, _phantom: Default::default(), } } pub fn begin_scope<'scope>( &'scope mut self, name: &'static str, ) -> ScopeEncoder<'enc, 'scope, CommandEncoder> where 'prof_enc: 'scope, { let scope_index = self.encoder.begin_scope(Some(self.scope_index), name); ScopeEncoder { encoder: self.encoder, scope_index, _phantom: Default::default(), } } pub fn end_scope(self) { drop(self); } } impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>> { pub fn begin_scope<'scope>( &'scope mut self, name: &'static str, ) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>> where 'prof_enc: 'scope, { let scope_index = self.encoder.begin_scope(Some(self.scope_index), name); ScopeEncoder { encoder: self.encoder, scope_index, _phantom: Default::default(), } } pub fn end_scope(self) { drop(self); } } impl<'enc, 'prof_enc, T> Drop for ScopeEncoder<'enc, 'prof_enc, T> { fn drop(&mut self) { if let Some((parent_scope, _)) = self.encoder.compute_pass && parent_scope == self.scope_index { // Finish compute pass by droping it self.encoder.compute_pass = None; } self.encoder.end_scope(self.scope_index); } } impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, CommandEncoder> { fn deref_mut(&mut self) -> &mut Self::Target { &mut *self.encoder } } impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, CommandEncoder> { type Target = CommandEncoder; fn deref(&self) -> &Self::Target { &*self.encoder } } impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.encoder.compute_pass.as_mut().unwrap().1 } } impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>> { type Target = ComputePass<'static>; fn deref(&self) -> &Self::Target { &self.encoder.compute_pass.as_ref().unwrap().1 } } impl<'enc> DerefMut for ProfilingEncoder<'enc> { fn deref_mut(&mut self) -> &mut Self::Target { self.encoder } } impl<'enc> Deref for ProfilingEncoder<'enc> { type Target = CommandEncoder; fn deref(&self) -> &Self::Target { self.encoder } } struct QuerySetAllocator { device: Device, current_size: u32, current_id: u32, query_sets: Vec<(u32, u32, QuerySet)>, } #[derive(PartialEq, Eq)] struct QuerySetHandle(usize, u32, u32); impl QuerySetHandle { pub fn index(&self) -> usize { self.2 as usize } } impl PartialOrd for QuerySetHandle { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for QuerySetHandle { fn cmp(&self, other: &Self) -> std::cmp::Ordering { match self.0.cmp(&other.0) { core::cmp::Ordering::Equal => {} ord => return ord, } self.1.cmp(&other.1) } } impl QuerySetAllocator { pub fn new(device: &Device) -> Self { let current_size = 32; let query_sets = vec![( 0, current_size, Self::new_query_set(device, current_size, 0), )]; QuerySetAllocator { query_sets, current_size, current_id: 0, device: device.clone(), } } pub fn allocated_count(&self) -> u32 { self.query_sets .iter() .map(|(allocated, _, _)| *allocated) .sum() } pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer) { let mut offset = 0; for (allocated, _, query_set) in self.query_sets.iter() { encoder.resolve_query_set(query_set, 0..*allocated, target, offset); offset += *allocated as u64 * size_of::() as u64; } } pub fn allocate(&mut self) -> QuerySetHandle { // Check if allocation is possible if self .query_sets .last() .is_some_and(|(allocated, available, _)| allocated == available) { // No more room, allocate new query set self.current_size *= 2; self.query_sets.push(( 0, self.current_size, Self::new_query_set(&self.device, self.current_size, self.query_sets.len()), )); } // Last allocation is guaranteed to have room let (allocated, _available, _query_set) = self.query_sets.last_mut().unwrap(); let query_index = *allocated; *allocated += 1; let query_set_index = self.query_sets.len() - 1; let id = self.current_id; self.current_id += 1; QuerySetHandle(query_set_index, query_index, id) } fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet { device.create_query_set(&wgpu::QuerySetDescriptor { label: Some(format!("QuerySetAllocator::query_set_{index}").as_str()), ty: wgpu::QueryType::Timestamp, count: size, }) } fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle) { let query_set = &self.query_sets[handle.0].2; encoder.write_timestamp(query_set, handle.1); } fn write_compute_timestamp(&mut self, pass: &mut ComputePass, handle: &QuerySetHandle) { let query_set = &self.query_sets[handle.0].2; pass.write_timestamp(query_set, handle.1); } } impl GpuProfile { pub fn read_back( self, device: &Device, queue: &Queue, mut callback: impl FnMut(Profile) + Send + Sync + 'static, ) { // Readback timestamps wgpu::util::DownloadBuffer::read_buffer( device, queue, &self.timestamps.slice(..), move |buffer| { let buffer = buffer.unwrap(); let timestamps: Vec = bytemuck::pod_collect_to_vec(&buffer); let start = timestamps.first().copied().unwrap_or(0); let frames = self .scopes .into_iter() .map(|scope| Frame { name: scope.name, children: scope.children, start_timestamp: timestamps[scope.start_index.index()] - start, end_timestamp: timestamps[scope.end_index.unwrap().index()] - start, }) .collect::>(); callback(Profile { frames }); }, ); } } impl Profile { pub fn to_display_string(&self, q: f32) -> String { let mut str = String::new(); self.frames[0].build_string(&self.frames, 0, q, &mut str); str } pub fn show(&self, ui: &mut Ui, q: f32) { if !self.frames.is_empty() { self.frames[0].show(ui, q, &self.frames); } } } impl Frame { fn time(&self, q: f32) -> f32 { (self.end_timestamp - self.start_timestamp) as f32 * q } fn start(&self, q: f32) -> f32 { self.start_timestamp as f32 * q } fn end(&self, q: f32) -> f32 { self.end_timestamp as f32 * q } fn build_string(&self, frames: &Vec, depth: usize, q: f32, str: &mut String) { let mut depth_string = String::new(); (0..depth).for_each(|_| depth_string.push_str(" ")); let time = (self.end_timestamp - self.start_timestamp) as f32 * q; str.push_str(&format!("{depth_string}{}: {:.2}\n", self.name, time)); self.children .iter() .for_each(|c| frames[*c].build_string(frames, depth + 1, q, str)); } pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec) { let id = ui.make_persistent_id(self.name); egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) .show_header(ui, |ui| { ui.horizontal(|ui| { ui.label(self.name); // Right-aligned label, laid out first from the right edge ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.label(format!("{:.2}ms", self.time(q))); // Whatever space remains between the two labels: // draw a thin line across it, vertically centered. let rect = ui.available_rect_before_wrap(); let y = rect.center().y; ui.painter().hline( rect.x_range(), y, ui.visuals().widgets.noninteractive.bg_stroke, ); }); }); }) .body(|ui| { self.children .iter() .for_each(|i| frames[*i].show(ui, q, frames)); }); } } impl Profile { // Clauderies pub fn show_flamegraph(&self, id: egui::Id, q: f32, ui: &mut Ui) -> egui::Response { if self.frames.is_empty() { return ui.label("empty"); } let row_height = 20.; // Full time range and max depth of the tree. let mut full = (f64::INFINITY, f64::NEG_INFINITY); let mut max_depth = 0usize; let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect(); while let Some((i, d)) = stack.pop() { let s = &self.frames[i]; full = (full.0.min(s.start(q) as f64), full.1.max(s.end(q) as f64)); max_depth = max_depth.max(d); stack.extend(s.children.iter().map(|&c| (c, d + 1))); } if full.0 >= full.1 { full = (0.0, 1.0); // empty or degenerate input } // The view is stored as fractions of the full range (not absolute times), so it // stays valid when the data changes from frame to frame. let fspan = full.1 - full.0; let norm: (f64, f64) = ui.data_mut(|d| d.get_temp(id)).unwrap_or((0.0, 1.0)); let mut view = (full.0 + norm.0 * fspan, full.0 + norm.1 * fspan); if !(view.1 > view.0) || !view.0.is_finite() || !view.1.is_finite() { view = full; } let size = vec2(ui.available_width(), (max_depth + 1) as f32 * row_height); let (resp, painter) = ui.allocate_painter(size, egui::Sense::click_and_drag()); let rect = resp.rect; let w = rect.width().max(1.0) as f64; // --- interaction --- let mut span = view.1 - view.0; if resp.dragged() { let dt = -(resp.drag_delta().x as f64) / w * span; view = (view.0 + dt, view.1 + dt); } if let Some(p) = resp.hover_pos() { let (zoom, scroll) = ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta.y)); let z = zoom as f64 * (scroll as f64 * 0.005).exp(); if (z - 1.0).abs() > 1e-6 { let frac = ((p.x - rect.left()) as f64 / w).clamp(0.0, 1.0); let t_cursor = view.0 + frac * span; span = (span / z).clamp((full.1 - full.0) * 1e-6, (full.1 - full.0) * 10.0); view = (t_cursor - frac * span, t_cursor + (1.0 - frac) * span); } } if resp.double_clicked() { view = full; } //ui.data_mut(|d| d.insert_temp(id, view)); ui.data_mut(|d| d.insert_temp(id, ((view.0 - full.0) / fspan, (view.1 - full.0) / fspan))); let span = view.1 - view.0; let to_x = |t: f64| rect.left() + ((t - view.0) / span) as f32 * rect.width(); // --- drawing --- painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color); let font = egui::FontId::proportional(12.0); let hover = resp.hover_pos(); let mut hovered: Option = None; let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect(); while let Some((i, depth)) = stack.pop() { let s = &self.frames[i]; let start = s.start(q) as f64; let end = s.end(q) as f64; if end < view.0 || start > view.1 { continue; // off-screen: children are inside the parent, skip them too } let (x0, x1) = (to_x(start).max(rect.left()), to_x(end).min(rect.right())); if x1 - x0 < 0.5 { continue; // too thin to see } let y = rect.top() + depth as f32 * row_height; let r = egui::Rect::from_min_max(egui::pos2(x0, y), egui::pos2(x1, y + row_height)) .shrink2(vec2(0.5, 0.5)); let is_hovered = hover.is_some_and(|p| r.contains(p)); if is_hovered { hovered = Some(i); } let mut color = color_for(&s.name); if is_hovered { color = color.gamma_multiply(1.15); } painter.rect_filled(r, 2.0, color); if r.width() > 24.0 { painter.with_clip_rect(r).text( r.left_center() + vec2(3.0, 0.0), egui::Align2::LEFT_CENTER, &s.name, font.clone(), egui::Color32::BLACK, ); } stack.extend(s.children.iter().map(|&c| (c, depth + 1))); } if let Some(i) = hovered { let s = &self.frames[i]; let start = s.start(q) as f64; let end = s.end(q) as f64; resp.clone().on_hover_ui_at_pointer(|ui| { ui.strong(s.name); ui.label(format!("duration: {:.3}", end - start)); ui.label(format!("start: {:.3} end: {:.3}", start, end)); }); } resp } } /// Stable pastel color derived from the scope name. fn color_for(name: &str) -> egui::Color32 { let mut h: u32 = 2166136261; // FNV-1a for b in name.bytes() { h = (h ^ b as u32).wrapping_mul(16777619); } egui::ecolor::Hsva::new((h % 360) as f32 / 360.0, 0.45, 0.9, 1.0).into() }