1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
//! Lightyear metrics Bevy UI (phase 1): minimal Bevy UI to visualize selected metrics
//! using native bevy_ui nodes, similar to diagnostics UI style.
//!
//! This reads metrics from `bevy_metrics_dashboard::registry::MetricsRegistry` and
//! displays a compact overlay. Phase 1 focuses on structure; phase 2 will expand metrics.
extern crate alloc;
use alloc::collections::VecDeque;
use alloc::format;
use alloc::string::ToString;
use alloc::{vec, vec::Vec};
use bevy_app::prelude::*;
use bevy_color::prelude::*;
use bevy_ecs::prelude::*;
use bevy_ecs::relationship::RelatedSpawnerCommands;
use bevy_reflect::prelude::Reflect;
use bevy_text::prelude::*;
use bevy_time::prelude::*;
use bevy_ui::prelude::*;
use bevy_utils::prelude::*;
use bevy_platform::collections::HashMap;
use lightyear_metrics::prelude::{ClearBucketsSystem, MetricsPlugin, MetricsRegistry};
use metrics::Key;
use metrics_util::{CompositeKey, MetricKind};
#[allow(unused_imports)]
use tracing::info;
#[derive(Resource, Debug, Reflect)]
#[reflect(Resource, Debug)]
pub struct MetricsPanelSettings {
pub enabled: bool,
/// Rolling window length for averages (number of frames/samples)
pub window_len: usize,
/// Alpha value for the background color
pub alpha: f32,
}
impl Default for MetricsPanelSettings {
fn default() -> Self {
Self {
enabled: true,
window_len: 50,
alpha: 0.2,
}
}
}
#[derive(Component)]
struct MetricsPanelRoot;
#[derive(Component)]
struct MetricLine {
spec: MetricSpec,
}
#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)]
pub enum MetricDirection {
Send,
Receive,
Neutral,
}
#[derive(Component)]
struct ValueText;
#[derive(Component)]
struct DirectionMarker(pub MetricDirection);
/// Specification for a single metric line in the UI.
#[derive(Clone)]
pub struct MetricSpec {
/// Display label for the line
pub label: &'static str,
/// Metrics registry key (supports fuzzy match)
pub key: CompositeKey,
/// If True, we need to divide the results per second
pub per_second: bool,
/// Direction of the metric
pub direction: MetricDirection,
}
impl MetricSpec {
const fn new(label: &'static str, key: CompositeKey) -> Self {
Self {
label,
key,
per_second: false,
direction: MetricDirection::Neutral,
}
}
fn with_per_second(mut self, per_second: bool) -> Self {
self.per_second = per_second;
self
}
fn with_direction(mut self, dir: MetricDirection) -> Self {
self.direction = dir;
self
}
}
/// A subsection of metrics within a section.
#[derive(Clone)]
pub struct MetricsSubsection {
pub title: &'static str,
pub items: Vec<MetricSpec>,
}
impl MetricsSubsection {
pub fn new(title: &'static str, items: Vec<MetricSpec>) -> Self {
Self { title, items }
}
}
/// A section that can contain multiple subsections.
#[derive(Clone)]
pub struct MetricsSection {
pub title: &'static str,
pub subsections: Vec<MetricsSubsection>,
}
impl MetricsSection {
pub fn new(title: &'static str, subsections: Vec<MetricsSubsection>) -> Self {
Self { title, subsections }
}
}
/// Resource configuring the layout (sections/subsections/items) for the metrics panel.
#[derive(Resource, Clone)]
pub struct MetricsPanelLayout {
pub sections: Vec<MetricsSection>,
}
impl Default for MetricsPanelLayout {
fn default() -> Self {
Self {
sections: vec![
MetricsSection::new(
"Profiler (ms)",
vec![
MetricsSubsection::new(
"Replication",
vec![
MetricSpec::new(
"Receive messages",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("replication/receive/time_ms"),
),
)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Apply to World",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("replication/apply/time_ms"),
),
)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Buffer messages",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("replication/buffer/time_ms"),
),
)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Send messages",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("replication/send/time_ms"),
),
)
.with_direction(MetricDirection::Send),
],
),
MetricsSubsection::new(
"Transport",
vec![
MetricSpec::new(
"Receive",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("transport/recv/time_ms"),
),
)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Send",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("transport/send/time_ms"),
),
)
.with_direction(MetricDirection::Send),
],
),
],
),
MetricsSection::new(
"Prediction",
vec![MetricsSubsection::new(
"Rollback",
vec![
MetricSpec::new(
"Count",
CompositeKey::new(
MetricKind::Counter,
Key::from_name("prediction/rollback/count"),
),
),
MetricSpec::new(
"Ticks",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("prediction/rollback/ticks"),
),
),
],
)],
),
MetricsSection::new(
"Bandwidth",
vec![
MetricsSubsection::new(
"Total",
vec![
MetricSpec::new(
"Send",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("transport/send_bytes"),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Recv",
CompositeKey::new(
MetricKind::Gauge,
Key::from_name("transport/recv_bytes"),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Packets lost",
CompositeKey::new(
MetricKind::Counter,
Key::from_name("transport/packets_lost"),
),
)
.with_direction(MetricDirection::Send),
],
),
MetricsSubsection::new(
"Replication",
vec![
MetricSpec::new(
"Send Actions (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_bytes",
&[(
"channel",
"lightyear_replication::message::ActionsChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Send Updates (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_bytes",
&[(
"channel",
"lightyear_replication::message::UpdatesChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Send Actions (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_messages",
&[(
"channel",
"lightyear_replication::message::ActionsChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Send Updates (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_messages",
&[(
"channel",
"lightyear_replication::message::UpdatesChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Recv Actions (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_bytes",
&[(
"channel",
"lightyear_replication::message::ActionsChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Recv Updates (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_bytes",
&[(
"channel",
"lightyear_replication::message::UpdatesChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Recv Actions (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_messages",
&[(
"channel",
"lightyear_replication::message::ActionsChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Recv Updates (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_messages",
&[(
"channel",
"lightyear_replication::message::UpdatesChannel",
)],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
],
),
MetricsSubsection::new(
"Inputs",
vec![
MetricSpec::new(
"Send Inputs (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_bytes",
&[("channel", "lightyear_inputs::InputChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Recv Inputs (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_bytes",
&[("channel", "lightyear_inputs::InputChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Send Inputs (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_messages",
&[("channel", "lightyear_inputs::InputChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Recv Inputs (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_messages",
&[("channel", "lightyear_inputs::InputChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
],
),
MetricsSubsection::new(
"Sync",
vec![
MetricSpec::new(
"Send Ping (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_bytes",
&[("channel", "lightyear_sync::ping::PingChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Recv Ping (bytes/s)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_bytes",
&[("channel", "lightyear_sync::ping::PingChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
MetricSpec::new(
"Send Ping (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/send_messages",
&[("channel", "lightyear_sync::ping::PingChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Send),
MetricSpec::new(
"Recv Ping (num messages)",
CompositeKey::new(
MetricKind::Gauge,
Key::from_parts(
"channel/recv_messages",
&[("channel", "lightyear_sync::ping::PingChannel")],
),
),
)
.with_per_second(true)
.with_direction(MetricDirection::Receive),
],
),
],
),
],
}
}
}
pub struct DebugUIPlugin;
impl Plugin for DebugUIPlugin {
fn build(&self, app: &mut App) {
if !app.is_plugin_added::<MetricsPlugin>() {
app.add_plugins(MetricsPlugin::default());
}
app.init_resource::<MetricsPanelSettings>();
app.init_resource::<MetricsPanelLayout>();
app.insert_resource(VisibilityFilter {
show_send: true,
show_recv: true,
});
app.init_resource::<CollapseState>();
app.add_systems(Startup, setup_metrics_panel);
app.init_resource::<MetricHistory>();
app.add_systems(
Last,
(
update_visibility,
handle_button_interactions,
update_collapsible_displays,
sample_metrics_history,
update_metrics,
)
.chain()
.before(ClearBucketsSystem),
);
}
}
#[derive(Component)]
struct SectionHeader {
id: u32,
}
#[derive(Component)]
struct SubsectionHeader {
id: u32,
}
#[derive(Component)]
struct CollapsibleContent {
id: u32,
}
#[derive(Resource, Default)]
struct CollapseState {
sections: HashMap<u32, bool>,
subsections: HashMap<u32, bool>,
}
#[derive(Resource, Default)]
struct VisibilityFilter {
show_send: bool,
show_recv: bool,
}
#[derive(Component)]
struct SendToggle;
#[derive(Component)]
struct RecvToggle;
#[derive(Component, Default)]
struct PerChannelInput;
fn setup_metrics_panel(
mut commands: Commands,
settings: Res<MetricsPanelSettings>,
layout: Res<MetricsPanelLayout>,
) {
commands
.spawn((
Name::new("Lightyear Metrics"),
MetricsPanelRoot,
Node {
position_type: PositionType::Absolute,
top: Val::Px(5.0),
right: Val::Px(5.0),
width: Val::Px(300.0),
padding: UiRect::all(Val::Px(8.0)),
display: if settings.enabled {
Display::Flex
} else {
Display::None
},
flex_direction: FlexDirection::Column,
row_gap: Val::Px(6.0),
..default()
},
BackgroundColor(Color::srgba(0.0, 0.0, 0.0, settings.alpha)),
BorderRadius::all(Val::Px(6.0)),
))
.with_children(|cmd| {
// Top controls row
cmd.spawn(Node {
display: Display::Flex,
justify_content: JustifyContent::SpaceBetween,
column_gap: Val::Px(8.0),
..default()
})
.with_children(|cmd| {
cmd.spawn((
SendToggle,
Button,
Text::new("Send"),
TextFont {
font_size: 10.0,
..default()
},
BackgroundColor(Color::srgba(0.0, 0.6, 0.0, settings.alpha)),
));
cmd.spawn((
RecvToggle,
Button,
Text::new("Receive"),
TextFont {
font_size: 10.0,
..default()
},
BackgroundColor(Color::srgba(0.0, 0.6, 0.0, settings.alpha)),
));
});
build_sections(cmd, &layout, &settings);
});
}
fn line(
cmd: &mut RelatedSpawnerCommands<ChildOf>,
spec: &MetricSpec,
settings: &MetricsPanelSettings,
) {
cmd.spawn((
MetricLine { spec: spec.clone() },
DirectionMarker(spec.direction),
Node {
display: Display::Flex,
justify_content: JustifyContent::SpaceBetween,
..default()
},
BackgroundColor(Color::srgba(0.32, 0.32, 0.32, settings.alpha)),
))
.with_children(|cmd| {
cmd.spawn((
Text::new(spec.label.to_string()),
TextFont {
font_size: 10.0,
..default()
},
));
cmd.spawn((
ValueText,
Text::new("-"),
TextFont {
font_size: 10.0,
..default()
},
));
});
}
fn build_sections(
cmd: &mut RelatedSpawnerCommands<ChildOf>,
layout: &MetricsPanelLayout,
settings: &MetricsPanelSettings,
) {
let mut section_id: u32 = 1;
let mut subsection_id: u32 = 1000;
for section in &layout.sections {
// Section header button
cmd.spawn((
SectionHeader { id: section_id },
Button,
Node {
display: Display::Flex,
justify_content: JustifyContent::SpaceBetween,
..default()
},
))
.with_children(|cmd| {
cmd.spawn((
Text::new(format!("> {}", section.title)),
TextFont {
font_size: 12.0,
..default()
},
TextColor(Color::srgba(0.9, 0.9, 0.9, settings.alpha)),
));
});
// Section content container
cmd.spawn((
CollapsibleContent { id: section_id },
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(4.0),
..default()
},
BackgroundColor(Color::srgba(0.12, 0.12, 0.12, settings.alpha)),
))
.with_children(|cmd| {
for subsection in §ion.subsections {
// Subsection header
cmd.spawn((
SubsectionHeader { id: subsection_id },
Button,
Node {
display: Display::Flex,
justify_content: JustifyContent::SpaceBetween,
..default()
},
))
.with_children(|cmd| {
cmd.spawn((
Text::new(format!("> {}", subsection.title)),
TextFont {
font_size: 11.0,
..default()
},
));
});
// Subsection content
cmd.spawn((
CollapsibleContent { id: subsection_id },
Node {
display: Display::Flex,
flex_direction: FlexDirection::Column,
row_gap: Val::Px(2.0),
..default()
},
BackgroundColor(Color::srgba(0.24, 0.24, 0.24, settings.alpha)),
))
.with_children(|cmd| {
for spec in &subsection.items {
line(cmd, spec, settings);
}
});
subsection_id += 1;
}
});
section_id += 1;
}
}
fn handle_button_interactions(
mut collapse: ResMut<CollapseState>,
mut vis: ResMut<VisibilityFilter>,
settings: Res<MetricsPanelSettings>,
mut uis: ParamSet<(
Query<(&SectionHeader, &mut Interaction, &mut Children)>,
Query<(&SubsectionHeader, &mut Interaction, &mut Children)>,
Query<(&mut Interaction, &mut BackgroundColor), With<SendToggle>>,
Query<(&mut Interaction, &mut BackgroundColor), With<RecvToggle>>,
Query<&mut Text>,
)>,
) {
// Section toggles
{
let section_events: Vec<(u32, Option<Entity>)> = {
let mut out = Vec::new();
for (header, interaction, children) in uis.p0().iter() {
if *interaction == Interaction::Pressed {
out.push((header.id, children.first().copied()));
}
}
out
};
for (id, first_child) in section_events {
let entry = collapse.sections.entry(id).or_insert(false);
*entry = !*entry;
if let Some(child) = first_child
&& let Ok(mut text) = uis.p4().get_mut(child)
{
let label = text
.0
.trim_start_matches('V')
.trim_start_matches('>')
.trim();
text.0 = if *entry {
format!("> {}", label)
} else {
format!("V {}", label)
};
}
}
// reset interactions
for (_h, mut interaction, _c) in &mut uis.p0() {
if *interaction == Interaction::Pressed {
*interaction = Interaction::None;
}
}
}
// Subsection toggles
{
let subsection_events: Vec<(u32, Option<Entity>)> = {
let mut out = Vec::new();
for (header, interaction, children) in uis.p1().iter() {
if *interaction == Interaction::Pressed {
out.push((header.id, children.first().copied()));
}
}
out
};
for (id, first_child) in subsection_events {
let entry = collapse.subsections.entry(id).or_insert(false);
*entry = !*entry;
if let Some(child) = first_child
&& let Ok(mut text) = uis.p4().get_mut(child)
{
let label = text
.0
.trim_start_matches('V')
.trim_start_matches('>')
.trim();
text.0 = if *entry {
format!("> {}", label)
} else {
format!("V {}", label)
};
}
}
for (_h, mut interaction, _c) in &mut uis.p1() {
if *interaction == Interaction::Pressed {
*interaction = Interaction::None;
}
}
}
// Send/Recv toggles
if let Ok((mut inter, mut bg)) = uis.p2().single_mut()
&& *inter == Interaction::Pressed
{
vis.show_send = !vis.show_send;
bg.0 = if vis.show_send {
Color::srgba(0.0, 0.6, 0.0, settings.alpha)
} else {
Color::srgba(0.2, 0.2, 0.2, settings.alpha)
};
*inter = Interaction::None;
}
if let Ok((mut inter, mut bg)) = uis.p3().single_mut()
&& *inter == Interaction::Pressed
{
vis.show_recv = !vis.show_recv;
bg.0 = if vis.show_recv {
Color::srgba(0.0, 0.6, 0.0, settings.alpha)
} else {
Color::srgba(0.2, 0.2, 0.2, settings.alpha)
};
*inter = Interaction::None;
}
}
fn update_collapsible_displays(
collapse: Res<CollapseState>,
mut q_cont: Query<(&CollapsibleContent, &mut Node)>,
) {
if !collapse.is_changed() {
return;
}
for (c, mut node) in &mut q_cont {
let collapsed = collapse.sections.get(&c.id).copied().unwrap_or(false)
|| collapse.subsections.get(&c.id).copied().unwrap_or(false);
node.display = if collapsed {
Display::None
} else {
Display::Flex
};
}
}
fn update_visibility(
settings: Res<MetricsPanelSettings>,
mut q: Query<&mut Node, With<MetricsPanelRoot>>,
) {
if !settings.is_changed() {
return;
}
for mut node in &mut q {
node.display = if settings.enabled {
Display::Flex
} else {
Display::None
};
}
}
// Update the metric text on the UI
fn update_metrics(
time: Res<Time<Real>>,
vis: Res<VisibilityFilter>,
mut q_lines: Query<(&MetricLine, &DirectionMarker, &mut Node, &Children)>,
mut q_values: Query<&mut Text, With<ValueText>>,
history: Res<MetricHistory>,
) {
// Section/subsection collapsing is handled by containers; here we only apply Send/Recv filtering
for (line, dir, mut node, children) in &mut q_lines {
// Filter by Send/Receive toggles
let show = match dir.0 {
MetricDirection::Send => vis.show_send,
MetricDirection::Receive => vis.show_recv,
MetricDirection::Neutral => true,
};
node.display = if show { Display::Flex } else { Display::None };
// Update value text
if show
&& let Some(buffer) = history.buffers.get(&line.spec.key.key().get_hash())
&& let Some(latest) = buffer.latest()
{
let avg = buffer.avg().unwrap();
if let Some(&child) = children.get(1)
&& let Ok(mut text) = q_values.get_mut(child)
{
text.0 = format!("{:.3} (avg {:.3})", latest, avg);
}
}
}
}
/// Resource storing rolling windows for metric samples
#[derive(Resource, Default)]
struct MetricHistory {
// the key is the hash of the metric key
buffers: HashMap<u64, MetricBuffer>,
}
#[derive(Default)]
struct MetricBuffer {
data: VecDeque<f64>,
sum: f64,
}
impl MetricBuffer {
fn push(&mut self, value: f64, cap: usize) {
self.data.push_back(value);
self.sum += value;
while self.data.len() > cap {
if let Some(v) = self.data.pop_front() {
self.sum -= v;
}
}
}
fn latest(&self) -> Option<f64> {
self.data.back().copied()
}
fn avg(&self) -> Option<f64> {
let sum = self.sum;
if self.data.is_empty() {
None
} else {
Some(sum / self.data.len() as f64)
}
}
}
/// Fetch the latest metric value from the MetricRegistry and push it to the history
fn sample_metrics_history(
time: Res<Time<Real>>,
registry: Res<MetricsRegistry>,
settings: Res<MetricsPanelSettings>,
mut history: ResMut<MetricHistory>,
q_lines: Query<&MetricLine>,
) {
let delta = time.delta().as_secs_f64();
let cap = settings.window_len.max(1);
for line in &q_lines {
if let Some(mut sample) = registry.fetch_metric_value(&line.spec.key) {
let key = line.spec.key.key().get_hash();
let buffer = history.buffers.entry(key).or_default();
if line.spec.per_second {
sample /= delta;
};
buffer.push(sample, cap);
// TODO: we might want to also do this for non-per-second metrics!
// if the metric is per second, we need to reset the value of the metric.
// The reason is that the metric could be incremented multiple times inside a single frame
// (for example if we receive multiple messages in the same channel of the same frame)
if line.spec.per_second {
registry.reset_metric(&line.spec.key);
}
}
}
}