1use std::time::Duration;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Stage {
29 Measured(Duration),
31 Unavailable(&'static str),
33 NotApplicable,
35}
36
37impl Stage {
38 pub fn is_measured(self) -> bool {
40 matches!(self, Stage::Measured(_))
41 }
42
43 pub fn duration(self) -> Option<Duration> {
45 match self {
46 Stage::Measured(d) => Some(d),
47 _ => None,
48 }
49 }
50
51 pub fn label(self) -> &'static str {
53 match self {
54 Stage::Measured(_) => "measured",
55 Stage::Unavailable(_) => "unavailable",
56 Stage::NotApplicable => "not_applicable",
57 }
58 }
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum StageId {
66 EventDispatch,
68 Layout,
70 AfterFrame,
72 RenderPrepare,
74 CommandGen,
76 CpuRaster,
78 Upload,
80 BackendSubmit,
82 PixelConvert,
84 ImageAlloc,
86 PixelCopy,
88 CanvasBlit,
90 PresentBlocking,
92 AfterPresent,
94 GpuExecute,
96 Compositor,
98 TotalFrame,
100}
101
102impl StageId {
103 pub const ALL: [StageId; 17] = [
105 StageId::EventDispatch,
106 StageId::Layout,
107 StageId::AfterFrame,
108 StageId::RenderPrepare,
109 StageId::CommandGen,
110 StageId::CpuRaster,
111 StageId::Upload,
112 StageId::BackendSubmit,
113 StageId::PixelConvert,
114 StageId::ImageAlloc,
115 StageId::PixelCopy,
116 StageId::CanvasBlit,
117 StageId::PresentBlocking,
118 StageId::AfterPresent,
119 StageId::GpuExecute,
120 StageId::Compositor,
121 StageId::TotalFrame,
122 ];
123
124 pub fn name(self) -> &'static str {
126 match self {
127 StageId::EventDispatch => "event_dispatch",
128 StageId::Layout => "layout",
129 StageId::AfterFrame => "after_frame",
130 StageId::RenderPrepare => "render_prepare",
131 StageId::CommandGen => "command_gen",
132 StageId::CpuRaster => "cpu_raster",
133 StageId::Upload => "upload",
134 StageId::BackendSubmit => "backend_submit",
135 StageId::PixelConvert => "pixel_convert",
136 StageId::ImageAlloc => "image_alloc",
137 StageId::PixelCopy => "pixel_copy",
138 StageId::CanvasBlit => "canvas_blit",
139 StageId::PresentBlocking => "present_blocking",
140 StageId::AfterPresent => "after_present",
141 StageId::GpuExecute => "gpu_execute",
142 StageId::Compositor => "compositor",
143 StageId::TotalFrame => "total_frame",
144 }
145 }
146}
147
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
153pub struct StageTimes {
154 pub event_dispatch: Option<Duration>,
156 pub layout: Option<Duration>,
158 pub after_frame: Option<Duration>,
160 pub render_prepare: Option<Duration>,
162 pub command_gen: Option<Duration>,
164 pub cpu_raster: Option<Duration>,
166 pub upload: Option<Duration>,
168 pub backend_submit: Option<Duration>,
170 pub pixel_convert: Option<Duration>,
172 pub image_alloc: Option<Duration>,
174 pub pixel_copy: Option<Duration>,
176 pub canvas_blit: Option<Duration>,
178 pub present_blocking: Option<Duration>,
180 pub after_present: Option<Duration>,
182 pub gpu_execute: Option<Duration>,
184 pub compositor: Option<Duration>,
186 pub total_frame: Option<Duration>,
188}
189
190impl StageTimes {
191 pub fn set(&mut self, id: StageId, value: Duration) {
196 match id {
197 StageId::EventDispatch => self.event_dispatch = Some(value),
198 StageId::Layout => self.layout = Some(value),
199 StageId::AfterFrame => self.after_frame = Some(value),
200 StageId::RenderPrepare => self.render_prepare = Some(value),
201 StageId::CommandGen => self.command_gen = Some(value),
202 StageId::CpuRaster => self.cpu_raster = Some(value),
203 StageId::Upload => self.upload = Some(value),
204 StageId::BackendSubmit => self.backend_submit = Some(value),
205 StageId::PixelConvert => self.pixel_convert = Some(value),
206 StageId::ImageAlloc => self.image_alloc = Some(value),
207 StageId::PixelCopy => self.pixel_copy = Some(value),
208 StageId::CanvasBlit => self.canvas_blit = Some(value),
209 StageId::PresentBlocking => self.present_blocking = Some(value),
210 StageId::AfterPresent => self.after_present = Some(value),
211 StageId::GpuExecute => self.gpu_execute = Some(value),
212 StageId::Compositor => self.compositor = Some(value),
213 StageId::TotalFrame => self.total_frame = Some(value),
214 }
215 }
216
217 pub fn get(&self, id: StageId) -> Option<Duration> {
219 match id {
220 StageId::EventDispatch => self.event_dispatch,
221 StageId::Layout => self.layout,
222 StageId::AfterFrame => self.after_frame,
223 StageId::RenderPrepare => self.render_prepare,
224 StageId::CommandGen => self.command_gen,
225 StageId::CpuRaster => self.cpu_raster,
226 StageId::Upload => self.upload,
227 StageId::PixelConvert => self.pixel_convert,
228 StageId::ImageAlloc => self.image_alloc,
229 StageId::PixelCopy => self.pixel_copy,
230 StageId::CanvasBlit => self.canvas_blit,
231 StageId::BackendSubmit => self.backend_submit,
232 StageId::PresentBlocking => self.present_blocking,
233 StageId::AfterPresent => self.after_present,
234 StageId::GpuExecute => self.gpu_execute,
235 StageId::Compositor => self.compositor,
236 StageId::TotalFrame => self.total_frame,
237 }
238 }
239
240 pub fn clear(&mut self) {
242 *self = StageTimes::default();
243 }
244}
245
246#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
248pub struct FrameCounters {
249 pub dirty_rect_count: u32,
251 pub damaged_pixels: u64,
253 pub instance_pushed: u32,
255 pub instance_drawn: u32,
257 pub batch_count: u32,
259 pub atlas_upload_bytes: u64,
261 pub frame_skipped: bool,
263 pub occluded: bool,
265}
266
267#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub enum BackendKind {
270 D3d11,
272 Soft,
274 X11,
276 Web,
278}
279
280#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282pub enum Capability {
283 Measurable,
285 Unavailable(&'static str),
287 NotApplicable(&'static str),
289}
290
291const MERGED_COMMAND_GEN: &str = "软渲染在同一调用里生成命令并写像素,无法分离(拆开即为伪造数据)";
302
303const D3D11_UNAVAILABLE: &[(StageId, &str)] = &[
305 (
306 StageId::GpuExecute,
307 "本阶段未实现 D3D11 timestamp/disjoint query(需新增 vtable 槽,单独立项)",
308 ),
309 (
310 StageId::Compositor,
311 "DWM 合成在 Present 返回后异步发生,无完成回执",
312 ),
313];
314const D3D11_NOT_APPLICABLE: &[(StageId, &str)] = &[
315 (StageId::CpuRaster, "GPU 后端不做 CPU 光栅化"),
316 (StageId::PixelConvert, "该阶段只在 Web 后端存在"),
317 (StageId::ImageAlloc, "该阶段只在 Web 后端存在"),
318 (StageId::PixelCopy, "该阶段只在 Web 后端存在"),
319 (StageId::CanvasBlit, "该阶段只在 Web 后端存在"),
320];
321
322const SOFT_UNAVAILABLE: &[(StageId, &str)] = &[
324 (StageId::CommandGen, MERGED_COMMAND_GEN),
325 (
326 StageId::Compositor,
327 "DWM 合成在 GDI blit 返回后异步发生,无完成回执",
328 ),
329];
330const SOFT_NOT_APPLICABLE: &[(StageId, &str)] = &[
331 (StageId::BackendSubmit, "CPU 后端没有独立的 GPU 提交阶段"),
332 (StageId::GpuExecute, "CPU 光栅化后端没有 GPU 执行阶段"),
333 (StageId::PixelConvert, "该阶段只在 Web 后端存在"),
334 (StageId::ImageAlloc, "该阶段只在 Web 后端存在"),
335 (StageId::PixelCopy, "该阶段只在 Web 后端存在"),
336 (StageId::CanvasBlit, "该阶段只在 Web 后端存在"),
337];
338
339const X11_UNAVAILABLE: &[(StageId, &str)] = &[
341 (StageId::CommandGen, MERGED_COMMAND_GEN),
342 (
343 StageId::Compositor,
344 "X server 绘制无回执(加每帧 XSync 会改变被测性能)",
345 ),
346];
347const X11_NOT_APPLICABLE: &[(StageId, &str)] = &[
348 (StageId::BackendSubmit, "CPU 后端没有独立的 GPU 提交阶段"),
349 (
350 StageId::PresentBlocking,
351 "X11 的上传与 Present 是同一个动作,已合并计入 upload",
352 ),
353 (StageId::GpuExecute, "CPU 光栅化后端没有 GPU 执行阶段"),
354 (StageId::PixelConvert, "该阶段只在 Web 后端存在"),
355 (StageId::ImageAlloc, "该阶段只在 Web 后端存在"),
356 (StageId::CanvasBlit, "该阶段只在 Web 后端存在"),
357 ];
362
363const WEB_UNAVAILABLE: &[(StageId, &str)] = &[
365 (StageId::CommandGen, MERGED_COMMAND_GEN),
366 (
367 StageId::Compositor,
368 "浏览器合成在 rAF 回调结束后发生,wasm 侧不可观测",
369 ),
370];
371const WEB_NOT_APPLICABLE: &[(StageId, &str)] = &[
372 (StageId::BackendSubmit, "CPU 后端没有独立的 GPU 提交阶段"),
373 (
374 StageId::Upload,
375 "Web 没有独立上传阶段,已拆成 pixel_convert / image_alloc / pixel_copy / canvas_blit",
376 ),
377 (
378 StageId::PresentBlocking,
379 "Web 的上屏是 canvas_blit(putImageData 调用本身),无阻塞式 Present",
380 ),
381 (StageId::GpuExecute, "CPU 光栅化后端没有 GPU 执行阶段"),
382];
383
384impl BackendKind {
385 pub fn unavailable_table(self) -> &'static [(StageId, &'static str)] {
387 match self {
388 BackendKind::D3d11 => D3D11_UNAVAILABLE,
389 BackendKind::Soft => SOFT_UNAVAILABLE,
390 BackendKind::X11 => X11_UNAVAILABLE,
391 BackendKind::Web => WEB_UNAVAILABLE,
392 }
393 }
394
395 pub fn not_applicable_table(self) -> &'static [(StageId, &'static str)] {
397 match self {
398 BackendKind::D3d11 => D3D11_NOT_APPLICABLE,
399 BackendKind::Soft => SOFT_NOT_APPLICABLE,
400 BackendKind::X11 => X11_NOT_APPLICABLE,
401 BackendKind::Web => WEB_NOT_APPLICABLE,
402 }
403 }
404
405 pub fn capability(self, id: StageId) -> Capability {
410 if let Some((_, reason)) = self.unavailable_table().iter().find(|(s, _)| *s == id) {
411 return Capability::Unavailable(reason);
412 }
413 if let Some((_, reason)) = self.not_applicable_table().iter().find(|(s, _)| *s == id) {
414 return Capability::NotApplicable(reason);
415 }
416 Capability::Measurable
417 }
418
419 pub fn declared_unavailable(self) -> Vec<(StageId, &'static str)> {
421 self.unavailable_table().to_vec()
422 }
423
424 pub fn declared_not_applicable(self) -> Vec<(StageId, &'static str)> {
426 self.not_applicable_table().to_vec()
427 }
428
429 pub fn name(self) -> &'static str {
431 match self {
432 BackendKind::D3d11 => "d3d11",
433 BackendKind::Soft => "soft",
434 BackendKind::X11 => "x11",
435 BackendKind::Web => "web",
436 }
437 }
438}
439
440impl Capability {
441 pub fn is_measurable(self) -> bool {
443 matches!(self, Capability::Measurable)
444 }
445}
446
447#[derive(Clone, Copy, Debug, PartialEq, Eq)]
449pub enum StatsError {
450 MeasuredButNotMeasurable {
452 stage: StageId,
454 reason: &'static str,
456 },
457 EmptyReason(StageId),
459 ConflictingTables(StageId),
461 UnavailableButNotApplicable(StageId),
463}
464
465#[derive(Clone, Copy, Debug)]
467pub struct RenderStats {
468 pub frame_id: u64,
470 pub backend: BackendKind,
472 pub presented: bool,
474 pub stages: StageTimes,
476 pub counters: FrameCounters,
478 pub frame_unavailable: &'static [(StageId, &'static str)],
480}
481
482impl RenderStats {
483 pub fn new(frame_id: u64, backend: BackendKind) -> Self {
485 Self {
486 frame_id,
487 backend,
488 presented: false,
489 stages: StageTimes::default(),
490 counters: FrameCounters::default(),
491 frame_unavailable: &[],
492 }
493 }
494
495 pub fn stage(&self, id: StageId) -> Stage {
500 if let Some(d) = self.stages.get(id) {
501 return Stage::Measured(d);
502 }
503 match self.backend.capability(id) {
504 Capability::NotApplicable(reason) => {
505 let _ = reason;
506 Stage::NotApplicable
507 }
508 Capability::Unavailable(reason) => Stage::Unavailable(reason),
509 Capability::Measurable => {
510 if let Some((_, reason)) = self.frame_unavailable.iter().find(|(s, _)| *s == id) {
511 return Stage::Unavailable(reason);
512 }
513 Stage::Unavailable("本帧未经过该阶段")
514 }
515 }
516 }
517
518 pub fn validate(&self) -> Result<(), StatsError> {
523 for id in StageId::ALL {
524 let measured = self.stages.get(id).is_some();
525 match self.backend.capability(id) {
526 Capability::Measurable => {}
527 Capability::Unavailable(reason) => {
528 if measured {
529 return Err(StatsError::MeasuredButNotMeasurable { stage: id, reason });
530 }
531 }
532 Capability::NotApplicable(reason) => {
533 if measured {
534 return Err(StatsError::MeasuredButNotMeasurable { stage: id, reason });
535 }
536 if self.frame_unavailable.iter().any(|(s, _)| *s == id) {
537 return Err(StatsError::UnavailableButNotApplicable(id));
538 }
539 }
540 }
541 }
542 for (id, reason) in self.frame_unavailable {
543 if reason.trim().is_empty() {
544 return Err(StatsError::EmptyReason(*id));
545 }
546 if matches!(self.backend.capability(*id), Capability::NotApplicable(_)) {
547 return Err(StatsError::UnavailableButNotApplicable(*id));
548 }
549 }
550 Ok(())
551 }
552
553 pub fn reset_for_next_frame(&mut self, frame_id: u64) {
557 self.frame_id = frame_id;
558 self.presented = false;
559 self.stages.clear();
560 self.counters = FrameCounters::default();
561 self.frame_unavailable = &[];
562 }
563
564 pub fn write_json(&self, out: &mut String) {
569 use std::fmt::Write;
570 let _ = write!(
571 out,
572 "{{\"frame\":{},\"backend\":\"{}\",\"presented\":{},\"stages\":{{",
573 self.frame_id,
574 self.backend.name(),
575 self.presented
576 );
577 let mut first = true;
578 for id in StageId::ALL {
579 let stage = self.stage(id);
580 if !first {
581 out.push(',');
582 }
583 first = false;
584 let _ = write!(out, "\"{}\":", id.name());
585 match stage {
586 Stage::Measured(d) => {
587 let _ = write!(out, "{}", d.as_secs_f64() * 1e6);
588 }
589 Stage::Unavailable(reason) => {
590 let _ = write!(out, "null");
591 let _ = write!(out, ",\"{}.unavailable\":\"{}\"", id.name(), reason);
592 }
593 Stage::NotApplicable => {
594 let _ = write!(out, "null,\"{}.not_applicable\":true", id.name());
595 }
596 }
597 }
598 let c = self.counters;
599 let _ = write!(
600 out,
601 "}},\"counters\":{{\"dirty_rects\":{},\"damaged_pixels\":{},\"instance_pushed\":{},\"instance_drawn\":{},\"batches\":{},\"atlas_bytes\":{},\"skipped\":{},\"occluded\":{}}}}}",
602 c.dirty_rect_count,
603 c.damaged_pixels,
604 c.instance_pushed,
605 c.instance_drawn,
606 c.batch_count,
607 c.atlas_upload_bytes,
608 c.frame_skipped,
609 c.occluded
610 );
611 }
612}
613
614pub const BACKEND_STAGES: [StageId; 12] = [
624 StageId::RenderPrepare,
625 StageId::CommandGen,
626 StageId::CpuRaster,
627 StageId::Upload,
628 StageId::BackendSubmit,
629 StageId::PixelConvert,
630 StageId::ImageAlloc,
631 StageId::PixelCopy,
632 StageId::CanvasBlit,
633 StageId::PresentBlocking,
634 StageId::GpuExecute,
635 StageId::Compositor,
636];
637
638impl RenderStats {
639 pub fn is_backend_stage(id: StageId) -> bool {
641 BACKEND_STAGES.contains(&id)
642 }
643
644 pub fn merge_backend(&mut self, src: Option<RenderStats>) -> bool {
659 let Some(src) = src else {
660 return false;
661 };
662 if src.backend != self.backend {
663 eprintln!(
665 "[y901] render_stats: 后端自报种类 {} 与本帧 {} 不一致,丢弃",
666 src.backend.name(),
667 self.backend.name()
668 );
669 return false;
670 }
671 for id in BACKEND_STAGES {
672 if let Some(d) = src.stages.get(id) {
673 self.stages.set(id, d);
674 }
675 }
676 self.counters = src.counters;
677 self.frame_unavailable = src.frame_unavailable;
683 if let Err(err) = self.validate() {
684 eprintln!("[y901] render_stats 自检失败,丢弃本帧后端数据:{err:?}");
685 self.frame_unavailable = &[];
686 }
687 true
688 }
689
690 pub fn backend_stage_sum(&self) -> Duration {
692 let mut sum = Duration::ZERO;
693 for id in BACKEND_STAGES {
694 if let Some(d) = self.stages.get(id) {
695 sum += d;
696 }
697 }
698 sum
699 }
700}
701pub fn enabled() -> bool {
709 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
710 *ON.get_or_init(|| {
711 std::env::var_os("Y901_RENDER_STATS").is_some_and(|v| v != "0" && !v.is_empty())
712 })
713}
714
715#[inline]
717pub fn mark(started: bool) -> Option<web_time::Instant> {
718 if started {
719 Some(web_time::Instant::now())
720 } else {
721 None
722 }
723}
724
725#[inline]
727pub fn since(start: Option<web_time::Instant>) -> Option<Duration> {
728 start.map(|s| s.elapsed())
729}
730
731#[inline]
733pub fn record(times: &mut StageTimes, id: StageId, start: Option<web_time::Instant>) {
734 if let Some(d) = since(start) {
735 times.set(id, d);
736 }
737}
738#[derive(Debug)]
751pub struct Collector {
752 stats: Option<RenderStats>,
753 frame: u64,
754 backend: BackendKind,
755}
756
757impl Collector {
758 pub fn new(backend: BackendKind) -> Self {
760 Self {
761 stats: None,
762 frame: 0,
763 backend,
764 }
765 }
766
767 pub fn begin_frame(&mut self) {
769 if enabled() {
770 self.frame = self.frame.wrapping_add(1);
771 match self.stats.as_mut() {
772 Some(s) => s.reset_for_next_frame(self.frame),
773 None => self.stats = Some(RenderStats::new(self.frame, self.backend)),
774 }
775 } else {
776 self.stats = None;
777 }
778 }
779
780 #[inline]
782 pub fn enabled(&self) -> bool {
783 self.stats.is_some()
784 }
785
786 #[inline]
788 pub fn mark(&self) -> Option<web_time::Instant> {
789 mark(self.stats.is_some())
790 }
791
792 #[inline]
794 pub fn record_elapsed(&mut self, id: StageId, elapsed: Option<Duration>) {
795 if let (Some(s), Some(d)) = (self.stats.as_mut(), elapsed) {
796 s.stages.set(id, d);
797 }
798 }
799
800 #[inline]
802 pub fn record(&mut self, id: StageId, start: Option<web_time::Instant>) {
803 if let Some(s) = self.stats.as_mut() {
804 record(&mut s.stages, id, start);
805 }
806 }
807
808 #[inline]
810 pub fn set_dirty(&mut self, rects: u32, pixels: u64) {
811 if let Some(s) = self.stats.as_mut() {
812 s.counters.dirty_rect_count = rects;
813 s.counters.damaged_pixels = pixels;
814 }
815 }
816
817 pub fn mark_skipped(&mut self) {
819 if let Some(s) = self.stats.as_mut() {
820 s.counters.frame_skipped = true;
821 }
822 }
823
824 pub fn finish(&mut self) {
829 if let Some(s) = self.stats.as_mut() {
830 s.counters.atlas_upload_bytes = 0;
831 s.counters.instance_pushed = 0;
832 s.counters.instance_drawn = 0;
833 s.counters.batch_count = 0;
834 s.counters.occluded = false;
835 s.counters.frame_skipped = false;
836 }
837 }
838
839 pub fn stats_mut(&mut self) -> &mut Option<RenderStats> {
846 &mut self.stats
847 }
848
849 pub fn take(&mut self) -> Option<RenderStats> {
851 self.stats.take()
852 }
853
854 pub fn discard(&mut self) {
856 self.stats = None;
857 }
858}
859
860#[cfg(test)]
861mod tests {
862 use super::*;
863
864 fn stats(backend: BackendKind) -> RenderStats {
865 RenderStats::new(7, backend)
866 }
867
868 #[test]
871 fn gpu_execute_can_never_be_reported_as_measured() {
872 for backend in [
873 BackendKind::D3d11,
874 BackendKind::Soft,
875 BackendKind::X11,
876 BackendKind::Web,
877 ] {
878 let mut s = stats(backend);
879 s.stages.set(StageId::GpuExecute, Duration::from_micros(3));
880 assert_eq!(
881 s.validate(),
882 Err(StatsError::MeasuredButNotMeasurable {
883 stage: StageId::GpuExecute,
884 reason: match backend.capability(StageId::GpuExecute) {
885 Capability::Unavailable(r) | Capability::NotApplicable(r) => r,
886 Capability::Measurable => unreachable!("GPU 阶段不该是可测量的"),
887 },
888 }),
889 "{backend:?} 上把 gpu_execute 填成 Measured 必须被 validate 拒绝"
890 );
891 }
892 }
893
894 #[test]
895 fn compositor_is_never_measurable_on_any_backend() {
896 for backend in [
897 BackendKind::D3d11,
898 BackendKind::Soft,
899 BackendKind::X11,
900 BackendKind::Web,
901 ] {
902 let mut s = stats(backend);
903 s.stages.set(StageId::Compositor, Duration::from_micros(1));
904 assert!(
905 s.validate().is_err(),
906 "{backend:?} 上 compositor 不可测,填值必须报错"
907 );
908 assert!(
909 !backend.capability(StageId::Compositor).is_measurable(),
910 "{backend:?} 的 compositor 能力声明必须不是 Measurable"
911 );
912 }
913 }
914
915 #[test]
918 fn unavailable_reasons_are_never_empty() {
919 for backend in [
921 BackendKind::D3d11,
922 BackendKind::Soft,
923 BackendKind::X11,
924 BackendKind::Web,
925 ] {
926 for (id, reason) in backend.declared_unavailable() {
927 assert!(
928 !reason.trim().is_empty(),
929 "{backend:?} 的 {} 声称不可用却没给原因",
930 id.name()
931 );
932 }
933 for (id, reason) in backend.declared_not_applicable() {
934 assert!(
935 !reason.trim().is_empty(),
936 "{backend:?} 的 {} 声称不适用却没给原因",
937 id.name()
938 );
939 }
940 }
941 let mut s = stats(BackendKind::D3d11);
943 s.frame_unavailable = &[(StageId::Upload, " ")];
944 assert_eq!(s.validate(), Err(StatsError::EmptyReason(StageId::Upload)));
945 }
946
947 #[test]
950 fn not_applicable_and_unavailable_are_distinct() {
951 let soft = stats(BackendKind::Soft);
953 assert_eq!(soft.stage(StageId::GpuExecute), Stage::NotApplicable);
954 assert_eq!(soft.stage(StageId::GpuExecute).label(), "not_applicable");
955 assert_ne!(soft.stage(StageId::GpuExecute).label(), "unavailable");
956
957 let d3d = stats(BackendKind::D3d11);
959 match d3d.stage(StageId::GpuExecute) {
960 Stage::Unavailable(reason) => assert!(!reason.trim().is_empty()),
961 other => panic!("D3D11 的 gpu_execute 应为 Unavailable,实际 {other:?}"),
962 }
963 assert_ne!(d3d.stage(StageId::GpuExecute), Stage::NotApplicable);
964
965 let idle = stats(BackendKind::D3d11);
967 match idle.stage(StageId::CommandGen) {
968 Stage::Unavailable(reason) => assert!(reason.contains("本帧未经过")),
969 other => panic!("未打点的可测阶段应为 Unavailable,实际 {other:?}"),
970 }
971 }
972
973 #[test]
976 fn measured_zero_is_legal_and_distinct_from_no_measurement() {
977 let mut s = stats(BackendKind::D3d11);
978 s.stages.set(StageId::CommandGen, Duration::ZERO);
979 assert_eq!(s.validate(), Ok(()), "零耗时是合法测量值");
980 assert_eq!(
981 s.stage(StageId::CommandGen),
982 Stage::Measured(Duration::ZERO)
983 );
984 assert!(s.stage(StageId::CommandGen).is_measured());
985 assert_eq!(s.stages.get(StageId::Upload), None);
987 assert!(!s.stage(StageId::Upload).is_measured());
988 }
989
990 #[test]
993 fn disabled_stats_produce_no_measurements() {
994 assert_eq!(mark(false), None);
996 assert_eq!(since(None), None);
997 let mut times = StageTimes::default();
998 record(&mut times, StageId::Layout, mark(false));
999 assert_eq!(times, StageTimes::default(), "关闭时不得写入任何阶段");
1000
1001 let s = stats(BackendKind::D3d11);
1004 assert_eq!(s.validate(), Ok(()));
1005 for id in StageId::ALL {
1006 assert!(
1007 !s.stage(id).is_measured(),
1008 "统计关闭时 {} 不应有测量值",
1009 id.name()
1010 );
1011 }
1012 }
1013
1014 #[test]
1015 fn enabled_mark_returns_a_timestamp_and_records_a_duration() {
1016 let t = mark(true);
1018 assert!(t.is_some(), "开启时 mark 必须返回时间戳");
1019 let mut times = StageTimes::default();
1020 record(&mut times, StageId::Layout, t);
1021 assert!(
1022 times.get(StageId::Layout).is_some(),
1023 "开启时 record 必须写入测量值"
1024 );
1025 assert!(since(t).is_some());
1026 }
1027
1028 #[test]
1031 fn set_overwrites_instead_of_accumulating() {
1032 let mut s = stats(BackendKind::D3d11);
1033 s.stages.set(StageId::Layout, Duration::from_micros(10));
1034 s.stages.set(StageId::Layout, Duration::from_micros(4));
1035 assert_eq!(
1036 s.stages.get(StageId::Layout),
1037 Some(Duration::from_micros(4))
1038 );
1039 }
1040
1041 #[test]
1042 fn every_stage_id_round_trips_through_set_and_get() {
1043 for id in StageId::ALL {
1044 let mut times = StageTimes::default();
1045 times.set(id, Duration::from_nanos(1));
1046 assert_eq!(
1047 times.get(id),
1048 Some(Duration::from_nanos(1)),
1049 "{}",
1050 id.name()
1051 );
1052 }
1053 assert_eq!(StageId::ALL.len(), 17);
1055 let mut names: Vec<&str> = StageId::ALL.iter().map(|i| i.name()).collect();
1057 names.sort_unstable();
1058 let before = names.len();
1059 names.dedup();
1060 assert_eq!(names.len(), before, "阶段名字必须唯一");
1061 }
1062
1063 #[test]
1064 fn reset_for_next_frame_clears_stages_and_counters_but_keeps_identity() {
1065 let mut s = stats(BackendKind::X11);
1066 s.stages.set(StageId::CpuRaster, Duration::from_micros(9));
1067 s.counters.dirty_rect_count = 3;
1068 s.counters.frame_skipped = true;
1069 s.presented = true;
1070 s.reset_for_next_frame(8);
1071 assert_eq!(s.frame_id, 8);
1072 assert_eq!(s.backend, BackendKind::X11, "后端身份不应被重置");
1073 assert_eq!(s.stages, StageTimes::default(), "上一帧的阶段必须清空");
1074 assert_eq!(s.counters, FrameCounters::default());
1075 assert!(!s.presented);
1076 }
1077
1078 #[test]
1084 fn merge_backend_never_touches_presented() {
1085 let mut runtime_stats = stats(BackendKind::D3d11);
1087 runtime_stats.presented = false;
1088
1089 let mut backend_stats = RenderStats::new(1, BackendKind::D3d11);
1091 backend_stats.presented = true;
1092 backend_stats
1093 .stages
1094 .set(StageId::BackendSubmit, Duration::from_micros(5));
1095
1096 assert!(runtime_stats.merge_backend(Some(backend_stats)));
1097 assert!(
1098 !runtime_stats.presented,
1099 "merge_backend 不得用后端的 presented 覆盖 Runtime 的值"
1100 );
1101 assert_eq!(
1103 runtime_stats.stages.get(StageId::BackendSubmit),
1104 Some(Duration::from_micros(5))
1105 );
1106
1107 let mut runtime_stats = stats(BackendKind::D3d11);
1109 runtime_stats.presented = true;
1110 let mut backend_stats = RenderStats::new(2, BackendKind::D3d11);
1111 backend_stats.presented = false;
1112 assert!(runtime_stats.merge_backend(Some(backend_stats)));
1113 assert!(
1114 runtime_stats.presented,
1115 "merge_backend 不得把 Runtime 的 presented 清成 false"
1116 );
1117 }
1118 #[test]
1119 fn frame_unavailable_can_explain_a_measurable_stage_this_frame() {
1120 let mut s = stats(BackendKind::D3d11);
1122 s.frame_unavailable = &[(StageId::Upload, "本帧图集未变化,无需上传")];
1123 assert_eq!(s.validate(), Ok(()));
1124 assert_eq!(
1125 s.stage(StageId::Upload),
1126 Stage::Unavailable("本帧图集未变化,无需上传")
1127 );
1128 }
1129
1130 #[test]
1131 fn unavailable_entry_for_not_applicable_stage_is_rejected() {
1132 let mut s = stats(BackendKind::Soft);
1133 s.frame_unavailable = &[(StageId::GpuExecute, "不该出现在这里")];
1134 assert_eq!(
1135 s.validate(),
1136 Err(StatsError::UnavailableButNotApplicable(StageId::GpuExecute))
1137 );
1138 }
1139
1140 #[test]
1144 fn collector_is_inert_when_disabled() {
1145 let mut c = Collector::new(BackendKind::X11);
1148 c.begin_frame();
1149 assert_eq!(c.enabled(), enabled(), "enabled() 必须与进程开关一致");
1150 assert_eq!(
1151 c.mark().is_some(),
1152 enabled(),
1153 "关闭时不得读时钟(mark 返回 None)"
1154 );
1155 c.record(StageId::Upload, None);
1157 c.set_dirty(3, 300);
1158 c.mark_skipped();
1159 c.finish();
1160 let stats = c.take();
1161 assert_eq!(stats.is_some(), enabled());
1162 assert!(c.take().is_none());
1164 }
1165
1166 #[test]
1168 fn collector_reuses_one_object_and_zeroes_cpu_counters() {
1169 if !enabled() {
1170 return;
1172 }
1173 let mut c = Collector::new(BackendKind::Soft);
1174 c.begin_frame();
1175 c.set_dirty(2, 200);
1176 c.record_elapsed(StageId::CpuRaster, Some(Duration::from_micros(5)));
1177 c.finish();
1178 let s = c.take().expect("应当交付统计");
1179 assert_eq!(s.backend, BackendKind::Soft);
1180 assert_eq!(s.counters.dirty_rect_count, 2);
1181 assert_eq!(s.counters.damaged_pixels, 200);
1182 assert_eq!(s.counters.atlas_upload_bytes, 0);
1183 assert!(!s.counters.frame_skipped);
1184 assert_eq!(
1185 s.stages.get(StageId::CpuRaster),
1186 Some(Duration::from_micros(5))
1187 );
1188 assert_eq!(s.validate(), Ok(()));
1189 c.begin_frame();
1191 let s2 = c.take().expect("第二帧");
1192 assert_eq!(s2.frame_id, s.frame_id + 1, "每帧帧号必须 +1");
1193 }
1194
1195 #[test]
1197 fn collector_skipped_frame_has_no_stage_values() {
1198 let mut c = Collector::new(BackendKind::Web);
1199 c.begin_frame();
1200 c.mark_skipped();
1201 if let Some(s) = c.take() {
1202 assert!(s.counters.frame_skipped);
1203 for id in StageId::ALL {
1204 assert_eq!(s.stages.get(id), None, "跳过帧不得有 {}", id.name());
1205 }
1206 assert_eq!(s.validate(), Ok(()));
1207 }
1208 }
1209
1210 #[test]
1212 fn collector_discard_prevents_delivery() {
1213 let mut c = Collector::new(BackendKind::X11);
1214 c.begin_frame();
1215 c.discard();
1216 assert!(c.take().is_none(), "discard 之后不得交付");
1217 }
1218
1219 #[test]
1220 fn json_never_prints_a_fake_zero_for_unmeasurable_stages() {
1221 let mut s = stats(BackendKind::D3d11);
1222 s.stages.set(StageId::CommandGen, Duration::ZERO);
1223 let mut out = String::new();
1224 s.write_json(&mut out);
1225 assert!(out.contains("\"command_gen\":0"), "真实 0 应输出 0:{out}");
1227 assert!(
1229 out.contains("\"gpu_execute\":null"),
1230 "gpu_execute 必须输出 null:{out}"
1231 );
1232 assert!(
1233 out.contains("gpu_execute.unavailable"),
1234 "gpu_execute 必须带不可用原因:{out}"
1235 );
1236 assert!(
1237 !out.contains("\"gpu_execute\":0"),
1238 "gpu_execute 不得输出 0:{out}"
1239 );
1240 let soft = stats(BackendKind::Soft);
1242 let mut out2 = String::new();
1243 soft.write_json(&mut out2);
1244 assert!(out2.contains("\"gpu_execute\":null"), "{out2}");
1245 assert!(out2.contains("gpu_execute.not_applicable"), "{out2}");
1246 }
1247
1248 #[test]
1249 fn d3d11_declares_gpu_and_compositor_unavailable() {
1250 let unavail = BackendKind::D3d11.declared_unavailable();
1251 assert!(unavail.iter().any(|(id, _)| *id == StageId::GpuExecute));
1252 assert!(unavail.iter().any(|(id, _)| *id == StageId::Compositor));
1253 assert!(BackendKind::D3d11
1255 .capability(StageId::BackendSubmit)
1256 .is_measurable());
1257 }
1258
1259 #[test]
1260 fn soft_backends_merge_command_generation_into_raster() {
1261 for backend in [BackendKind::Soft, BackendKind::X11, BackendKind::Web] {
1263 let cap = backend.capability(StageId::CommandGen);
1264 assert!(
1265 !cap.is_measurable(),
1266 "{backend:?} 不应把 command_gen 声明为可测量"
1267 );
1268 assert!(
1269 backend.capability(StageId::CpuRaster).is_measurable(),
1270 "{backend:?} 的 cpu_raster 必须可测"
1271 );
1272 }
1273 assert!(BackendKind::D3d11
1275 .capability(StageId::CommandGen)
1276 .is_measurable());
1277 assert!(!BackendKind::D3d11
1278 .capability(StageId::CpuRaster)
1279 .is_measurable());
1280 }
1281
1282 #[test]
1283 fn web_only_pixel_stages_do_not_exist_on_other_backends() {
1284 for id in [
1291 StageId::PixelConvert,
1292 StageId::ImageAlloc,
1293 StageId::CanvasBlit,
1294 ] {
1295 assert!(
1296 BackendKind::Web.capability(id).is_measurable(),
1297 "Web 的 {} 必须可测",
1298 id.name()
1299 );
1300 assert_eq!(
1301 BackendKind::X11.capability(id),
1302 Capability::NotApplicable("该阶段只在 Web 后端存在"),
1303 "X11 上 {} 必须是不适用",
1304 id.name()
1305 );
1306 for other in [BackendKind::D3d11, BackendKind::Soft] {
1307 match other.capability(id) {
1308 Capability::NotApplicable(reason) => {
1309 assert!(!reason.trim().is_empty(), "不适用必须给原因")
1310 }
1311 cap => panic!(
1312 "{other:?} 上 {} 应为不适用(这是 Web 独有阶段),实际 {cap:?}",
1313 id.name()
1314 ),
1315 }
1316 }
1317 }
1318
1319 assert!(
1321 BackendKind::X11
1322 .capability(StageId::PixelCopy)
1323 .is_measurable(),
1324 "X11 每帧要把像素拷到暂存再上屏,pixel_copy 必须可测"
1325 );
1326 assert!(
1327 BackendKind::Web
1328 .capability(StageId::PixelCopy)
1329 .is_measurable(),
1330 "Web 的 pixel_copy 必须可测"
1331 );
1332 for other in [BackendKind::D3d11, BackendKind::Soft] {
1334 assert!(
1335 !other.capability(StageId::PixelCopy).is_measurable(),
1336 "{other:?} 不该声称 pixel_copy 可测"
1337 );
1338 }
1339 }
1340}