1use std::cell::Cell;
3
4#[derive(Clone, Copy, Debug, Default)]
5pub struct PhysicsWork {
6 pub steps: u64,
7 pub candidate_pairs: u64,
8 pub contact_points: u64,
9 pub ccd_impacts: u64,
10}
11thread_local! {static PHYSICS: Cell<PhysicsWork> = Cell::new(PhysicsWork::default());}
12pub fn record_physics(pairs: usize, contacts: usize, ccd: usize) {
14 PHYSICS.with(|cell| {
15 let mut v = cell.get();
16 v.steps += 1;
17 v.candidate_pairs += pairs as u64;
18 v.contact_points += contacts as u64;
19 v.ccd_impacts += ccd as u64;
20 cell.set(v);
21 });
22}
23pub fn take_physics() -> PhysicsWork {
24 PHYSICS.with(|cell| cell.replace(PhysicsWork::default()))
25}
26
27#[cfg(not(target_arch = "wasm32"))]
28mod recording {
29 use super::*;
30 use std::{
31 alloc::{GlobalAlloc, Layout, System},
32 path::PathBuf,
33 sync::atomic::{AtomicBool, AtomicU64, Ordering},
34 time::Instant,
35 };
36 static ENABLED: AtomicBool = AtomicBool::new(false);
37 static CALLS: AtomicU64 = AtomicU64::new(0);
38 static BYTES: AtomicU64 = AtomicU64::new(0);
39 pub struct TrackingAllocator;
42 fn allocated(ptr: *mut u8, bytes: usize) {
43 if !ptr.is_null() && ENABLED.load(Ordering::Relaxed) {
44 CALLS.fetch_add(1, Ordering::Relaxed);
45 BYTES.fetch_add(bytes as u64, Ordering::Relaxed);
46 }
47 }
48 unsafe impl GlobalAlloc for TrackingAllocator {
50 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
51 let p = unsafe { System.alloc(layout) };
52 allocated(p, layout.size());
53 p
54 }
55 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
56 let p = unsafe { System.alloc_zeroed(layout) };
57 allocated(p, layout.size());
58 p
59 }
60 unsafe fn realloc(&self, p: *mut u8, layout: Layout, size: usize) -> *mut u8 {
61 let p = unsafe { System.realloc(p, layout, size) };
62 allocated(p, size);
63 p
64 }
65 unsafe fn dealloc(&self, p: *mut u8, layout: Layout) {
66 unsafe { System.dealloc(p, layout) };
67 }
68 }
69
70 thread_local! {
71 static LOCAL_ACTIVE: Cell<bool> = const { Cell::new(false) };
72 static LOCAL_CALLS: Cell<usize> = const { Cell::new(0) };
73 static LOCAL_BYTES: Cell<usize> = const { Cell::new(0) };
74 }
75 pub struct LocalAllocCounter;
87 fn record_local(ptr: *mut u8, bytes: usize) {
88 if !ptr.is_null() {
89 let _ = LOCAL_ACTIVE.try_with(|active| {
90 if active.get() {
91 let _ = LOCAL_CALLS.try_with(|c| c.set(c.get() + 1));
92 let _ = LOCAL_BYTES.try_with(|b| b.set(b.get().saturating_add(bytes)));
93 }
94 });
95 }
96 }
97 unsafe impl GlobalAlloc for LocalAllocCounter {
100 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
101 let p = unsafe { System.alloc(layout) };
102 record_local(p, layout.size());
103 p
104 }
105 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
106 let p = unsafe { System.alloc_zeroed(layout) };
107 record_local(p, layout.size());
108 p
109 }
110 unsafe fn realloc(&self, p: *mut u8, layout: Layout, size: usize) -> *mut u8 {
111 let p = unsafe { System.realloc(p, layout, size) };
112 record_local(p, size);
113 p
114 }
115 unsafe fn dealloc(&self, p: *mut u8, layout: Layout) {
116 unsafe { System.dealloc(p, layout) };
117 }
118 }
119 pub struct ThreadAllocScope {
122 prev_active: bool,
123 prev_calls: usize,
124 prev_bytes: usize,
125 }
126 impl ThreadAllocScope {
127 pub fn begin() -> Self {
128 Self {
129 prev_active: LOCAL_ACTIVE.with(|c| c.replace(true)),
130 prev_calls: LOCAL_CALLS.with(|c| c.replace(0)),
131 prev_bytes: LOCAL_BYTES.with(|c| c.replace(0)),
132 }
133 }
134 pub fn calls(&self) -> usize {
135 LOCAL_CALLS.with(Cell::get)
136 }
137 pub fn bytes(&self) -> usize {
138 LOCAL_BYTES.with(Cell::get)
139 }
140 pub fn finish(self) -> usize {
141 let calls = self.calls();
142 drop(self);
143 calls
144 }
145 }
146 impl Drop for ThreadAllocScope {
147 fn drop(&mut self) {
148 LOCAL_ACTIVE.with(|c| c.set(self.prev_active));
149 LOCAL_CALLS.with(|c| c.set(self.prev_calls));
150 LOCAL_BYTES.with(|c| c.set(self.prev_bytes));
151 }
152 }
153 pub fn count_thread_allocations<R>(f: impl FnOnce() -> R) -> (R, usize) {
156 let (result, calls, _) = count_thread_allocations_with_bytes(f);
157 (result, calls)
158 }
159 pub fn count_thread_allocations_with_bytes<R>(f: impl FnOnce() -> R) -> (R, usize, usize) {
162 let scope = ThreadAllocScope::begin();
163 let result = f();
164 let calls = scope.calls();
165 let bytes = scope.bytes();
166 drop(scope);
167 (result, calls, bytes)
168 }
169 #[derive(Clone, Debug, Default)]
170 pub struct FrameSample {
171 pub cpu_us: f64,
172 pub submit_us: Option<f64>,
174 pub software_render_us: Option<f64>,
175 pub gpu_us: Option<f64>,
176 pub draw_calls: Option<u64>,
177 pub vertices: Option<u64>,
178 pub upload_bytes: Option<u64>,
179 pub allocation_calls: u64,
180 pub allocation_bytes: u64,
181 pub physics: PhysicsWork,
182 }
183 pub struct FrameToken {
184 start: Instant,
185 calls: u64,
186 bytes: u64,
187 }
188 impl FrameToken {
189 pub fn begin() -> Self {
190 take_physics();
191 Self {
192 start: Instant::now(),
193 calls: CALLS.load(Ordering::Relaxed),
194 bytes: BYTES.load(Ordering::Relaxed),
195 }
196 }
197 pub fn elapsed_us(&self) -> f64 {
198 self.start.elapsed().as_secs_f64() * 1e6
199 }
200 pub fn finish(self, mut sample: FrameSample) -> FrameSample {
201 sample.allocation_calls = CALLS.load(Ordering::Relaxed).saturating_sub(self.calls);
202 sample.allocation_bytes = BYTES.load(Ordering::Relaxed).saturating_sub(self.bytes);
203 sample.physics = take_physics();
204 sample
205 }
206 }
207 pub struct Session {
209 output: PathBuf,
210 warmup: usize,
211 seen: usize,
212 dropped: usize,
213 samples: Vec<FrameSample>,
214 gpu_source: Option<&'static str>,
215 render_quality: Option<u32>,
216 }
217 impl Session {
218 pub fn from_env() -> Option<Self> {
219 let output = std::env::var_os("FERRAVEX_PERF_OUTPUT")?;
220 let warmup = std::env::var("FERRAVEX_PERF_WARMUP")
221 .map_or(60, |s| {
222 s.parse::<usize>().expect("invalid FERRAVEX_PERF_WARMUP")
223 })
224 .min(100_000);
225 let session = Self {
226 output: output.into(),
227 warmup,
228 seen: 0,
229 dropped: 0,
230 samples: Vec::with_capacity(8192),
231 gpu_source: None,
232 render_quality: None,
233 };
234 ENABLED.store(true, Ordering::Relaxed);
235 Some(session)
236 }
237 pub fn record(&mut self, sample: FrameSample) {
238 self.seen += 1;
239 if self.seen <= self.warmup {
240 return;
241 }
242 if self.samples.len() < self.samples.capacity() {
243 self.samples.push(sample);
244 } else {
245 self.dropped += 1;
246 }
247 }
248 pub fn render_quality(&mut self, quality: u32) {
249 self.render_quality = Some(quality);
250 }
251 pub fn gpu_source(&mut self, source: &'static str) {
252 self.gpu_source = Some(source);
253 }
254 pub fn gpu_result(&mut self, frame: u64, microseconds: f64) {
256 if !microseconds.is_finite() || microseconds < 0. || frame <= self.warmup as u64 {
257 return;
258 }
259 let index = frame - self.warmup as u64 - 1;
260 if let Some(sample) = self.samples.get_mut(index as usize) {
261 sample.gpu_us = Some(microseconds);
262 }
263 }
264 pub fn write(&self, backend: &str, width: u32, height: u32) -> std::io::Result<()> {
265 let mut out = format!(
266 "{{\"schema\":2,\"backend\":{},\"os\":{},\"arch\":{},\"width\":{width},\"height\":{height},\"warmup\":{},\"dropped\":{},\"gpu_source\":{},\"render_quality\":{},\"frames\":[",
267 json_string(backend),
268 json_string(std::env::consts::OS),
269 json_string(std::env::consts::ARCH),
270 self.warmup,
271 self.dropped,
272 self.gpu_source.map_or_else(|| "null".into(), json_string),
273 optional(self.render_quality)
274 );
275 for (i, s) in self.samples.iter().enumerate() {
276 if i > 0 {
277 out.push(',');
278 }
279 out.push_str(&format!("{{\"cpu_us\":{},\"submit_us\":{},\"software_render_us\":{},\"draw_calls\":{},\"vertices\":{},\"upload_bytes\":{},\"allocation_calls\":{},\"allocation_bytes\":{},\"physics_steps\":{},\"physics_pairs\":{},\"contact_points\":{},\"ccd_impacts\":{},\"gpu_us\":{}}}",s.cpu_us,optional(s.submit_us),optional(s.software_render_us),optional(s.draw_calls),optional(s.vertices),optional(s.upload_bytes),s.allocation_calls,s.allocation_bytes,s.physics.steps,s.physics.candidate_pairs,s.physics.contact_points,s.physics.ccd_impacts,optional(s.gpu_us)));
280 }
281 out.push_str("]}\n");
282 std::fs::write(&self.output, out)
283 }
284 }
285 fn optional<T: std::fmt::Display>(v: Option<T>) -> String {
286 v.map_or_else(|| "null".into(), |n| n.to_string())
287 }
288 pub fn json_string(value: &str) -> String {
289 let mut out = String::from("\"");
290 for c in value.chars() {
291 match c {
292 '"' => out.push_str("\\\""),
293 '\\' => out.push_str("\\\\"),
294 c if c < ' ' => out.push_str(&format!("\\u{:04x}", c as u32)),
295 c => out.push(c),
296 }
297 }
298 out.push('"');
299 out
300 }
301 #[cfg(test)]
302 mod tests {
303 use super::*;
304 #[test]
305 fn counters_sum_catchup_ticks_and_reset() {
306 take_physics();
307 record_physics(3, 4, 1);
308 record_physics(2, 5, 0);
309 let v = take_physics();
310 assert_eq!(
311 (v.steps, v.candidate_pairs, v.contact_points, v.ccd_impacts),
312 (2, 5, 9, 1)
313 );
314 assert_eq!(take_physics().steps, 0);
315 }
316 #[test]
317 fn strings_are_json_safe() {
318 assert_eq!(json_string("a\n\"\\\0"), "\"a\\u000a\\\"\\\\\\u0000\"");
319 }
320 #[test]
321 fn warmup_and_capacity_are_explicit() {
322 let mut s = Session {
323 output: PathBuf::new(),
324 warmup: 2,
325 seen: 0,
326 dropped: 0,
327 samples: Vec::with_capacity(2),
328 gpu_source: None,
329 render_quality: None,
330 };
331 for _ in 0..5 {
332 s.record(FrameSample::default());
333 }
334 assert_eq!((s.samples.len(), s.dropped), (2, 1));
335 s.gpu_result(2, 999.); s.gpu_result(4, 17.);
337 s.gpu_result(3, 12.);
338 s.gpu_result(3, f64::NAN);
339 s.gpu_result(4, -1.);
340 s.gpu_result(8, 4.); assert_eq!(s.samples[0].gpu_us, Some(12.));
342 assert_eq!(s.samples[1].gpu_us, Some(17.));
343 }
344 }
345}
346#[cfg(not(target_arch = "wasm32"))]
347pub use recording::*;