-
Notifications
You must be signed in to change notification settings - Fork 248
/
lib.rs
1134 lines (1033 loc) · 40.4 KB
/
lib.rs
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![warn(missing_docs)]
//! This crate provides an [Egui](https://github.com/emilk/egui) integration for the [Bevy](https://github.com/bevyengine/bevy) game engine.
//!
//! **Trying out:**
//!
//! An example WASM project is live at [mvlabat.github.io/bevy_egui_web_showcase](https://mvlabat.github.io/bevy_egui_web_showcase/index.html) [[source](https://github.com/mvlabat/bevy_egui_web_showcase)].
//!
//! **Features:**
//! - Desktop and web platforms support
//! - Clipboard (web support is limited to the same window, see [rust-windowing/winit#1829](https://github.com/rust-windowing/winit/issues/1829))
//! - Opening URLs
//! - Multiple windows support (see [./examples/two_windows.rs](https://github.com/mvlabat/bevy_egui/blob/v0.20.1/examples/two_windows.rs))
//!
//! `bevy_egui` can be compiled with using only `bevy` and `egui` as dependencies: `manage_clipboard` and `open_url` features,
//! that require additional crates, can be disabled.
//!
//! ## Usage
//!
//! Here's a minimal usage example:
//!
//! ```no_run,rust
//! use bevy::prelude::*;
//! use bevy_egui::{egui, EguiContexts, EguiPlugin};
//!
//! fn main() {
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_plugins(EguiPlugin)
//! // Systems that create Egui widgets should be run during the `CoreSet::Update` set,
//! // or after the `EguiSet::BeginPass` system (which belongs to the `CoreSet::PreUpdate` set).
//! .add_systems(Update, ui_example_system)
//! .run();
//! }
//!
//! fn ui_example_system(mut contexts: EguiContexts) {
//! egui::Window::new("Hello").show(contexts.ctx_mut(), |ui| {
//! ui.label("world");
//! });
//! }
//! ```
//!
//! For a more advanced example, see [examples/ui.rs](https://github.com/mvlabat/bevy_egui/blob/v0.20.1/examples/ui.rs).
//!
//! ```bash
//! cargo run --example ui
//! ```
//!
//! ## See also
//!
//! - [`bevy-inspector-egui`](https://github.com/jakobhellermann/bevy-inspector-egui)
#[cfg(all(
feature = "manage_clipboard",
target_arch = "wasm32",
not(web_sys_unstable_apis)
))]
compile_error!(include_str!("../static/error_web_sys_unstable_apis.txt"));
/// Egui render node.
#[cfg(feature = "render")]
pub mod egui_node;
/// Egui render node for rendering to a texture.
#[cfg(feature = "render")]
pub mod egui_render_to_texture_node;
/// Plugin systems for the render app.
#[cfg(feature = "render")]
pub mod render_systems;
/// Plugin systems.
pub mod systems;
/// Mobile web keyboard hacky input support
#[cfg(target_arch = "wasm32")]
mod text_agent;
/// Clipboard management for web
#[cfg(all(
feature = "manage_clipboard",
target_arch = "wasm32",
web_sys_unstable_apis
))]
pub mod web_clipboard;
pub use egui;
use crate::systems::*;
#[cfg(feature = "render")]
use crate::{
egui_node::{EguiPipeline, EGUI_SHADER_HANDLE},
render_systems::{EguiTransforms, ExtractedEguiManagedTextures},
};
#[cfg(all(
feature = "manage_clipboard",
not(any(target_arch = "wasm32", target_os = "android"))
))]
use arboard::Clipboard;
#[cfg(feature = "render")]
use bevy_asset::{load_internal_asset, AssetEvent, Assets, Handle};
#[cfg(feature = "render")]
use bevy_render::{
extract_component::{ExtractComponent, ExtractComponentPlugin},
extract_resource::{ExtractResource, ExtractResourcePlugin},
render_resource::SpecializedRenderPipelines,
texture::{Image, ImageSampler},
ExtractSchedule, Render, RenderApp, RenderSet,
};
use bevy_app::prelude::*;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{
prelude::*,
query::{QueryData, QueryEntityError},
schedule::apply_deferred,
system::SystemParam,
};
use bevy_input::InputSystem;
use bevy_reflect::Reflect;
use bevy_window::{PrimaryWindow, Window};
#[cfg(all(
feature = "manage_clipboard",
not(any(target_arch = "wasm32", target_os = "android"))
))]
use std::cell::{RefCell, RefMut};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
use crate::text_agent::{
install_text_agent, is_mobile_safari, process_safari_virtual_keyboard, propagate_text,
SafariVirtualKeyboardHack, TextAgentChannel, VirtualTouchInfo,
};
/// Adds all Egui resources and render graph nodes.
pub struct EguiPlugin;
/// A component for storing Egui context settings.
#[derive(Clone, Debug, Component, Reflect)]
#[cfg_attr(feature = "render", derive(ExtractComponent))]
pub struct EguiSettings {
/// Controls if Egui is run manually.
///
/// If set to `true`, a user is expected to call [`egui::Context::run`] or [`egui::Context::begin_pass`] and [`egui::Context::end_pass`] manually.
pub run_manually: bool,
/// Global scale factor for Egui widgets (`1.0` by default).
///
/// This setting can be used to force the UI to render in physical pixels regardless of DPI as follows:
/// ```rust
/// use bevy::{prelude::*, window::PrimaryWindow};
/// use bevy_egui::EguiSettings;
///
/// fn update_ui_scale_factor(mut windows: Query<(&mut EguiSettings, &Window), With<PrimaryWindow>>) {
/// if let Ok((mut egui_settings, window)) = windows.get_single_mut() {
/// egui_settings.scale_factor = 1.0 / window.scale_factor();
/// }
/// }
/// ```
pub scale_factor: f32,
/// Is used as a default value for hyperlink [target](https://www.w3schools.com/tags/att_a_target.asp) hints.
/// If not specified, `_self` will be used. Only matters in a web browser.
#[cfg(feature = "open_url")]
pub default_open_url_target: Option<String>,
}
// Just to keep the PartialEq
impl PartialEq for EguiSettings {
#[allow(clippy::let_and_return)]
fn eq(&self, other: &Self) -> bool {
let eq = self.scale_factor == other.scale_factor;
#[cfg(feature = "open_url")]
let eq = eq && self.default_open_url_target == other.default_open_url_target;
eq
}
}
impl Default for EguiSettings {
fn default() -> Self {
Self {
run_manually: false,
scale_factor: 1.0,
#[cfg(feature = "open_url")]
default_open_url_target: None,
}
}
}
/// Is used for storing Egui context input.
///
/// It gets reset during the [`EguiSet::ProcessInput`] system.
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct EguiInput(pub egui::RawInput);
/// Is used to store Egui context output.
#[derive(Component, Clone, Default, Deref, DerefMut)]
pub struct EguiFullOutput(pub Option<egui::FullOutput>);
/// A resource for accessing clipboard.
///
/// The resource is available only if `manage_clipboard` feature is enabled.
#[cfg(all(feature = "manage_clipboard", not(target_os = "android")))]
#[derive(Default, bevy_ecs::system::Resource)]
pub struct EguiClipboard {
#[cfg(not(target_arch = "wasm32"))]
clipboard: thread_local::ThreadLocal<Option<RefCell<Clipboard>>>,
#[cfg(all(target_arch = "wasm32", web_sys_unstable_apis))]
clipboard: web_clipboard::WebClipboard,
}
#[cfg(all(
feature = "manage_clipboard",
not(target_os = "android"),
not(all(target_arch = "wasm32", not(web_sys_unstable_apis)))
))]
impl EguiClipboard {
/// Sets clipboard contents.
pub fn set_contents(&mut self, contents: &str) {
self.set_contents_impl(contents);
}
/// Sets the internal buffer of clipboard contents.
/// This buffer is used to remember the contents of the last "Paste" event.
#[cfg(all(target_arch = "wasm32", web_sys_unstable_apis))]
pub fn set_contents_internal(&mut self, contents: &str) {
self.clipboard.set_contents_internal(contents);
}
/// Gets clipboard contents. Returns [`None`] if clipboard provider is unavailable or returns an error.
#[must_use]
#[cfg(not(target_arch = "wasm32"))]
pub fn get_contents(&mut self) -> Option<String> {
self.get_contents_impl()
}
/// Gets clipboard contents. Returns [`None`] if clipboard provider is unavailable or returns an error.
#[must_use]
#[cfg(all(target_arch = "wasm32", web_sys_unstable_apis))]
pub fn get_contents(&mut self) -> Option<String> {
self.get_contents_impl()
}
/// Receives a clipboard event sent by the `copy`/`cut`/`paste` listeners.
#[cfg(all(target_arch = "wasm32", web_sys_unstable_apis))]
pub fn try_receive_clipboard_event(&self) -> Option<web_clipboard::WebClipboardEvent> {
self.clipboard.try_receive_clipboard_event()
}
#[cfg(not(target_arch = "wasm32"))]
fn set_contents_impl(&mut self, contents: &str) {
if let Some(mut clipboard) = self.get() {
if let Err(err) = clipboard.set_text(contents.to_owned()) {
bevy_log::error!("Failed to set clipboard contents: {:?}", err);
}
}
}
#[cfg(all(target_arch = "wasm32", web_sys_unstable_apis))]
fn set_contents_impl(&mut self, contents: &str) {
self.clipboard.set_contents(contents);
}
#[cfg(not(target_arch = "wasm32"))]
fn get_contents_impl(&mut self) -> Option<String> {
if let Some(mut clipboard) = self.get() {
match clipboard.get_text() {
Ok(contents) => return Some(contents),
Err(err) => bevy_log::error!("Failed to get clipboard contents: {:?}", err),
}
};
None
}
#[cfg(all(target_arch = "wasm32", web_sys_unstable_apis))]
#[allow(clippy::unnecessary_wraps)]
fn get_contents_impl(&mut self) -> Option<String> {
self.clipboard.get_contents()
}
#[cfg(not(target_arch = "wasm32"))]
fn get(&self) -> Option<RefMut<Clipboard>> {
self.clipboard
.get_or(|| {
Clipboard::new()
.map(RefCell::new)
.map_err(|err| {
bevy_log::error!("Failed to initialize clipboard: {:?}", err);
})
.ok()
})
.as_ref()
.map(|cell| cell.borrow_mut())
}
}
/// Is used for storing Egui shapes and textures delta.
#[derive(Component, Clone, Default, Debug)]
#[cfg_attr(feature = "render", derive(ExtractComponent))]
pub struct EguiRenderOutput {
/// Pairs of rectangles and paint commands.
///
/// The field gets populated during the [`EguiSet::ProcessOutput`] system (belonging to bevy's [`PostUpdate`]) and reset during `EguiNode::update`.
pub paint_jobs: Vec<egui::ClippedPrimitive>,
/// The change in egui textures since last frame.
pub textures_delta: egui::TexturesDelta,
}
impl EguiRenderOutput {
/// Returns `true` if the output has no Egui shapes and no textures delta
pub fn is_empty(&self) -> bool {
self.paint_jobs.is_empty() && self.textures_delta.is_empty()
}
}
/// Is used for storing Egui output.
#[derive(Component, Clone, Default)]
pub struct EguiOutput {
/// The field gets updated during the [`EguiSet::ProcessOutput`] system (belonging to [`PostUpdate`]).
pub platform_output: egui::PlatformOutput,
}
/// A component for storing `bevy_egui` context.
#[derive(Clone, Component, Default)]
#[cfg_attr(feature = "render", derive(ExtractComponent))]
pub struct EguiContext {
ctx: egui::Context,
mouse_position: egui::Pos2,
pointer_touch_id: Option<u64>,
has_sent_ime_enabled: bool,
}
impl EguiContext {
/// Borrows the underlying Egui context immutably.
///
/// Even though the mutable borrow isn't necessary, as the context is wrapped into `RwLock`,
/// using the immutable getter is gated with the `immutable_ctx` feature. Using the immutable
/// borrow is discouraged as it may cause unpredictable blocking in UI systems.
///
/// When the context is queried with `&mut EguiContext`, the Bevy scheduler is able to make
/// sure that the context isn't accessed concurrently and can perform other useful work
/// instead of busy-waiting.
#[cfg(feature = "immutable_ctx")]
#[must_use]
pub fn get(&self) -> &egui::Context {
&self.ctx
}
/// Borrows the underlying Egui context mutably.
///
/// Even though the mutable borrow isn't necessary, as the context is wrapped into `RwLock`,
/// using the immutable getter is gated with the `immutable_ctx` feature. Using the immutable
/// borrow is discouraged as it may cause unpredictable blocking in UI systems.
///
/// When the context is queried with `&mut EguiContext`, the Bevy scheduler is able to make
/// sure that the context isn't accessed concurrently and can perform other useful work
/// instead of busy-waiting.
#[must_use]
pub fn get_mut(&mut self) -> &mut egui::Context {
&mut self.ctx
}
}
#[cfg(not(feature = "render"))]
type EguiContextsFilter = With<Window>;
#[cfg(feature = "render")]
type EguiContextsFilter = Or<(With<Window>, With<EguiRenderToTextureHandle>)>;
#[derive(SystemParam)]
/// A helper SystemParam that provides a way to get [`EguiContext`] with less boilerplate and
/// combines a proxy interface to the [`EguiUserTextures`] resource.
pub struct EguiContexts<'w, 's> {
q: Query<
'w,
's,
(
Entity,
&'static mut EguiContext,
Option<&'static PrimaryWindow>,
),
EguiContextsFilter,
>,
#[cfg(feature = "render")]
user_textures: ResMut<'w, EguiUserTextures>,
}
impl EguiContexts<'_, '_> {
/// Egui context of the primary window.
#[must_use]
pub fn ctx_mut(&mut self) -> &mut egui::Context {
self.try_ctx_mut()
.expect("`EguiContexts::ctx_mut` was called for an uninitialized context (primary window), make sure your system is run after [`EguiSet::InitContexts`] (or [`EguiStartupSet::InitContexts`] for startup systems)")
}
/// Fallible variant of [`EguiContexts::ctx_mut`].
#[must_use]
pub fn try_ctx_mut(&mut self) -> Option<&mut egui::Context> {
self.q
.iter_mut()
.find_map(|(_window_entity, ctx, primary_window)| {
if primary_window.is_some() {
Some(ctx.into_inner().get_mut())
} else {
None
}
})
}
/// Egui context of a specific entity.
#[must_use]
pub fn ctx_for_entity_mut(&mut self, enity: Entity) -> &mut egui::Context {
self.try_ctx_for_entity_mut(enity)
.unwrap_or_else(|| panic!("`EguiContexts::ctx_for_window_mut` was called for an uninitialized context (entity {enity:?}), make sure your system is run after [`EguiSet::InitContexts`] (or [`EguiStartupSet::InitContexts`] for startup systems)"))
}
/// Fallible variant of [`EguiContexts::ctx_for_entity_mut`].
#[must_use]
#[track_caller]
pub fn try_ctx_for_entity_mut(&mut self, entity: Entity) -> Option<&mut egui::Context> {
self.q
.iter_mut()
.find_map(|(window_entity, ctx, _primary_window)| {
if window_entity == entity {
Some(ctx.into_inner().get_mut())
} else {
None
}
})
}
/// Allows to get multiple contexts at the same time. This function is useful when you want
/// to get multiple window contexts without using the `immutable_ctx` feature.
#[track_caller]
pub fn ctx_for_entities_mut<const N: usize>(
&mut self,
ids: [Entity; N],
) -> Result<[&mut egui::Context; N], QueryEntityError> {
self.q
.get_many_mut(ids)
.map(|arr| arr.map(|(_window_entity, ctx, _primary_window)| ctx.into_inner().get_mut()))
}
/// Egui context of the primary window.
///
/// Even though the mutable borrow isn't necessary, as the context is wrapped into `RwLock`,
/// using the immutable getter is gated with the `immutable_ctx` feature. Using the immutable
/// borrow is discouraged as it may cause unpredictable blocking in UI systems.
///
/// When the context is queried with `&mut EguiContext`, the Bevy scheduler is able to make
/// sure that the context isn't accessed concurrently and can perform other useful work
/// instead of busy-waiting.
#[cfg(feature = "immutable_ctx")]
#[must_use]
pub fn ctx(&self) -> &egui::Context {
self.try_ctx()
.expect("`EguiContexts::ctx` was called for an uninitialized context (primary window), make sure your system is run after [`EguiSet::InitContexts`] (or [`EguiStartupSet::InitContexts`] for startup systems)")
}
/// Fallible variant of [`EguiContexts::ctx`].
///
/// Even though the mutable borrow isn't necessary, as the context is wrapped into `RwLock`,
/// using the immutable getter is gated with the `immutable_ctx` feature. Using the immutable
/// borrow is discouraged as it may cause unpredictable blocking in UI systems.
///
/// When the context is queried with `&mut EguiContext`, the Bevy scheduler is able to make
/// sure that the context isn't accessed concurrently and can perform other useful work
/// instead of busy-waiting.
#[cfg(feature = "immutable_ctx")]
#[must_use]
pub fn try_ctx(&self) -> Option<&egui::Context> {
self.q
.iter()
.find_map(|(_window_entity, ctx, primary_window)| {
if primary_window.is_some() {
Some(ctx.get())
} else {
None
}
})
}
/// Egui context of a specific window.
///
/// Even though the mutable borrow isn't necessary, as the context is wrapped into `RwLock`,
/// using the immutable getter is gated with the `immutable_ctx` feature. Using the immutable
/// borrow is discouraged as it may cause unpredictable blocking in UI systems.
///
/// When the context is queried with `&mut EguiContext`, the Bevy scheduler is able to make
/// sure that the context isn't accessed concurrently and can perform other useful work
/// instead of busy-waiting.
#[must_use]
#[cfg(feature = "immutable_ctx")]
pub fn ctx_for_entity(&self, entity: Entity) -> &egui::Context {
self.try_ctx_for_entity(entity)
.unwrap_or_else(|| panic!("`EguiContexts::ctx_for_entity` was called for an uninitialized context (entity {entity:?}), make sure your system is run after [`EguiSet::InitContexts`] (or [`EguiStartupSet::InitContexts`] for startup systems)"))
}
/// Fallible variant of [`EguiContexts::ctx_for_entity`].
///
/// Even though the mutable borrow isn't necessary, as the context is wrapped into `RwLock`,
/// using the immutable getter is gated with the `immutable_ctx` feature. Using the immutable
/// borrow is discouraged as it may cause unpredictable blocking in UI systems.
///
/// When the context is queried with `&mut EguiContext`, the Bevy scheduler is able to make
/// sure that the context isn't accessed concurrently and can perform other useful work
/// instead of busy-waiting.
#[must_use]
#[track_caller]
#[cfg(feature = "immutable_ctx")]
pub fn try_ctx_for_entity(&self, entity: Entity) -> Option<&egui::Context> {
self.q
.iter()
.find_map(|(window_entity, ctx, _primary_window)| {
if window_entity == entity {
Some(ctx.get())
} else {
None
}
})
}
/// Can accept either a strong or a weak handle.
///
/// You may want to pass a weak handle if you control removing texture assets in your
/// application manually and you don't want to bother with cleaning up textures in Egui.
///
/// You'll want to pass a strong handle if a texture is used only in Egui and there are no
/// handle copies stored anywhere else.
#[cfg(feature = "render")]
pub fn add_image(&mut self, image: Handle<Image>) -> egui::TextureId {
self.user_textures.add_image(image)
}
/// Removes the image handle and an Egui texture id associated with it.
#[cfg(feature = "render")]
#[track_caller]
pub fn remove_image(&mut self, image: &Handle<Image>) -> Option<egui::TextureId> {
self.user_textures.remove_image(image)
}
/// Returns an associated Egui texture id.
#[cfg(feature = "render")]
#[must_use]
#[track_caller]
pub fn image_id(&self, image: &Handle<Image>) -> Option<egui::TextureId> {
self.user_textures.image_id(image)
}
}
/// Contains the texture [`Image`] to render to.
#[cfg(feature = "render")]
#[derive(Component, Clone, Debug, ExtractComponent)]
pub struct EguiRenderToTextureHandle(pub Handle<Image>);
/// A resource for storing `bevy_egui` user textures.
#[derive(Clone, bevy_ecs::system::Resource, Default, ExtractResource)]
#[cfg(feature = "render")]
pub struct EguiUserTextures {
textures: bevy_utils::HashMap<Handle<Image>, u64>,
last_texture_id: u64,
}
#[cfg(feature = "render")]
impl EguiUserTextures {
/// Can accept either a strong or a weak handle.
///
/// You may want to pass a weak handle if you control removing texture assets in your
/// application manually and you don't want to bother with cleaning up textures in Egui.
///
/// You'll want to pass a strong handle if a texture is used only in Egui and there are no
/// handle copies stored anywhere else.
pub fn add_image(&mut self, image: Handle<Image>) -> egui::TextureId {
let id = *self.textures.entry(image.clone()).or_insert_with(|| {
let id = self.last_texture_id;
bevy_log::debug!("Add a new image (id: {}, handle: {:?})", id, image);
self.last_texture_id += 1;
id
});
egui::TextureId::User(id)
}
/// Removes the image handle and an Egui texture id associated with it.
pub fn remove_image(&mut self, image: &Handle<Image>) -> Option<egui::TextureId> {
let id = self.textures.remove(image);
bevy_log::debug!("Remove image (id: {:?}, handle: {:?})", id, image);
id.map(egui::TextureId::User)
}
/// Returns an associated Egui texture id.
#[must_use]
pub fn image_id(&self, image: &Handle<Image>) -> Option<egui::TextureId> {
self.textures
.get(image)
.map(|&id| egui::TextureId::User(id))
}
}
/// Stores physical size and scale factor, is used as a helper to calculate logical size.
#[derive(Component, Debug, Default, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "render", derive(ExtractComponent))]
pub struct RenderTargetSize {
/// Physical width
pub physical_width: f32,
/// Physical height
pub physical_height: f32,
/// Scale factor
pub scale_factor: f32,
}
impl RenderTargetSize {
fn new(physical_width: f32, physical_height: f32, scale_factor: f32) -> Self {
Self {
physical_width,
physical_height,
scale_factor,
}
}
/// Returns the width of the render target.
#[inline]
pub fn width(&self) -> f32 {
self.physical_width / self.scale_factor
}
/// Returns the height of the render target.
#[inline]
pub fn height(&self) -> f32 {
self.physical_height / self.scale_factor
}
}
/// The names of `bevy_egui` nodes.
pub mod node {
/// The main egui pass.
pub const EGUI_PASS: &str = "egui_pass";
}
#[derive(SystemSet, Clone, Hash, Debug, Eq, PartialEq)]
/// The `bevy_egui` plugin startup system sets.
pub enum EguiStartupSet {
/// Initializes Egui contexts for available windows.
InitContexts,
}
/// The `bevy_egui` plugin system sets.
#[derive(SystemSet, Clone, Hash, Debug, Eq, PartialEq)]
pub enum EguiSet {
/// Initializes Egui contexts for newly created render targets.
InitContexts,
/// Reads Egui inputs (keyboard, mouse, etc) and writes them into the [`EguiInput`] resource.
///
/// To modify the input, you can hook your system like this:
///
/// `system.after(EguiSet::ProcessInput).before(EguiSet::BeginPass)`.
ProcessInput,
/// Begins the `egui` pass.
BeginPass,
/// Processes the [`EguiOutput`] resource.
ProcessOutput,
}
impl Plugin for EguiPlugin {
fn build(&self, app: &mut App) {
app.register_type::<EguiSettings>();
#[cfg(feature = "render")]
{
app.init_resource::<EguiManagedTextures>();
app.init_resource::<EguiUserTextures>();
app.add_plugins(ExtractResourcePlugin::<EguiUserTextures>::default());
app.add_plugins(ExtractResourcePlugin::<ExtractedEguiManagedTextures>::default());
app.add_plugins(ExtractComponentPlugin::<EguiContext>::default());
app.add_plugins(ExtractComponentPlugin::<EguiSettings>::default());
app.add_plugins(ExtractComponentPlugin::<RenderTargetSize>::default());
app.add_plugins(ExtractComponentPlugin::<EguiRenderOutput>::default());
app.add_plugins(ExtractComponentPlugin::<EguiRenderToTextureHandle>::default());
}
#[cfg(target_arch = "wasm32")]
app.init_non_send_resource::<SubscribedEvents>();
#[cfg(all(feature = "manage_clipboard", not(target_os = "android")))]
app.init_resource::<EguiClipboard>();
#[cfg(all(
feature = "manage_clipboard",
target_arch = "wasm32",
web_sys_unstable_apis
))]
{
app.add_systems(PreStartup, web_clipboard::startup_setup_web_events);
}
app.add_systems(
PreStartup,
(
setup_new_windows_system,
setup_render_to_texture_handles_system,
apply_deferred,
update_contexts_system,
)
.chain()
.in_set(EguiStartupSet::InitContexts),
);
app.add_systems(
PreUpdate,
(
setup_new_windows_system,
setup_render_to_texture_handles_system,
apply_deferred,
update_contexts_system,
)
.chain()
.in_set(EguiSet::InitContexts),
);
app.add_systems(
PreUpdate,
process_input_system
.in_set(EguiSet::ProcessInput)
.after(InputSystem)
.after(EguiSet::InitContexts),
);
#[cfg(target_arch = "wasm32")]
{
use std::sync::{LazyLock, Mutex};
let maybe_window_plugin = app.get_added_plugins::<bevy_window::WindowPlugin>();
if !maybe_window_plugin.is_empty()
&& maybe_window_plugin[0].primary_window.is_some()
&& maybe_window_plugin[0]
.primary_window
.as_ref()
.unwrap()
.prevent_default_event_handling
{
app.init_resource::<TextAgentChannel>();
let (sender, receiver) = crossbeam_channel::unbounded();
static TOUCH_INFO: LazyLock<Mutex<VirtualTouchInfo>> =
LazyLock::new(|| Mutex::new(VirtualTouchInfo::default()));
app.insert_resource(SafariVirtualKeyboardHack {
sender,
receiver,
touch_info: &TOUCH_INFO,
});
app.add_systems(
PreStartup,
install_text_agent
.in_set(EguiSet::ProcessInput)
.after(process_input_system)
.after(InputSystem)
.after(EguiSet::InitContexts),
);
app.add_systems(
PreUpdate,
propagate_text
.in_set(EguiSet::ProcessInput)
.after(process_input_system)
.after(InputSystem)
.after(EguiSet::InitContexts),
);
if is_mobile_safari() {
app.add_systems(
PostUpdate,
process_safari_virtual_keyboard.after(process_output_system),
);
}
}
}
app.add_systems(
PreUpdate,
begin_pass_system
.in_set(EguiSet::BeginPass)
.after(EguiSet::ProcessInput),
);
app.add_systems(PostUpdate, end_pass_system.before(EguiSet::ProcessOutput));
app.add_systems(
PostUpdate,
process_output_system.in_set(EguiSet::ProcessOutput),
);
#[cfg(feature = "render")]
app.add_systems(
PostUpdate,
update_egui_textures_system.after(EguiSet::ProcessOutput),
)
.add_systems(
Render,
render_systems::prepare_egui_transforms_system.in_set(RenderSet::Prepare),
)
.add_systems(
Render,
render_systems::queue_bind_groups_system.in_set(RenderSet::Queue),
)
.add_systems(
Render,
render_systems::queue_pipelines_system.in_set(RenderSet::Queue),
)
.add_systems(Last, free_egui_textures_system);
#[cfg(feature = "render")]
load_internal_asset!(
app,
EGUI_SHADER_HANDLE,
"egui.wgsl",
bevy_render::render_resource::Shader::from_wgsl
);
}
#[cfg(feature = "render")]
fn finish(&self, app: &mut App) {
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
render_app
.init_resource::<egui_node::EguiPipeline>()
.init_resource::<SpecializedRenderPipelines<EguiPipeline>>()
.init_resource::<EguiTransforms>()
.add_systems(
ExtractSchedule,
(
render_systems::setup_new_windows_render_system,
render_systems::setup_new_rtt_render_system,
),
)
.add_systems(
Render,
render_systems::prepare_egui_transforms_system.in_set(RenderSet::Prepare),
)
.add_systems(
Render,
render_systems::queue_bind_groups_system.in_set(RenderSet::Queue),
)
.add_systems(
Render,
render_systems::queue_pipelines_system.in_set(RenderSet::Queue),
);
}
}
}
/// Queries all the Egui related components.
#[derive(QueryData)]
#[query_data(mutable)]
#[non_exhaustive]
pub struct EguiContextQuery {
/// Window entity.
pub render_target: Entity,
/// Egui context associated with the render target.
pub ctx: &'static mut EguiContext,
/// Settings associated with the context.
pub egui_settings: &'static mut EguiSettings,
/// Encapsulates [`egui::RawInput`].
pub egui_input: &'static mut EguiInput,
/// Encapsulates [`egui::FullOutput`].
pub egui_full_output: &'static mut EguiFullOutput,
/// Egui shapes and textures delta.
pub render_output: &'static mut EguiRenderOutput,
/// Encapsulates [`egui::PlatformOutput`].
pub egui_output: &'static mut EguiOutput,
/// Stores physical size of the window and its scale factor.
pub render_target_size: &'static mut RenderTargetSize,
/// [`Window`] component, when rendering to a window.
pub window: Option<&'static mut Window>,
/// [`EguiRenderToTextureHandle`] component, when rendering to a texture.
#[cfg(feature = "render")]
pub render_to_texture: Option<&'static mut EguiRenderToTextureHandle>,
}
impl EguiContextQueryItem<'_> {
fn ime_event_enable(&mut self) {
if !self.ctx.has_sent_ime_enabled {
self.egui_input
.events
.push(egui::Event::Ime(egui::ImeEvent::Enabled));
self.ctx.has_sent_ime_enabled = true;
}
}
fn ime_event_disable(&mut self) {
if self.ctx.has_sent_ime_enabled {
self.egui_input
.events
.push(egui::Event::Ime(egui::ImeEvent::Disabled));
self.ctx.has_sent_ime_enabled = false;
}
}
}
/// Contains textures allocated and painted by Egui.
#[cfg(feature = "render")]
#[derive(bevy_ecs::system::Resource, Deref, DerefMut, Default)]
pub struct EguiManagedTextures(pub bevy_utils::HashMap<(Entity, u64), EguiManagedTexture>);
/// Represents a texture allocated and painted by Egui.
#[cfg(feature = "render")]
pub struct EguiManagedTexture {
/// Assets store handle.
pub handle: Handle<Image>,
/// Stored in full so we can do partial updates (which bevy doesn't support).
pub color_image: egui::ColorImage,
}
/// Adds bevy_egui components to newly created windows.
pub fn setup_new_windows_system(
mut commands: Commands,
new_windows: Query<Entity, (Added<Window>, Without<EguiContext>)>,
) {
for window in new_windows.iter() {
commands.entity(window).insert((
EguiContext::default(),
EguiSettings::default(),
EguiRenderOutput::default(),
EguiInput::default(),
EguiFullOutput::default(),
EguiOutput::default(),
RenderTargetSize::default(),
));
}
}
/// Adds bevy_egui components to newly created windows.
pub fn setup_render_to_texture_handles_system(
mut commands: Commands,
#[cfg(feature = "render")] new_render_to_texture_targets: Query<
Entity,
(Added<EguiRenderToTextureHandle>, Without<EguiContext>),
>,
#[cfg(not(feature = "render"))] new_render_to_texture_targets: Query<
Entity,
Without<EguiContext>,
>,
) {
for render_to_texture_target in new_render_to_texture_targets.iter() {
commands.entity(render_to_texture_target).insert((
EguiContext::default(),
EguiSettings::default(),
EguiRenderOutput::default(),
EguiInput::default(),
EguiFullOutput::default(),
EguiOutput::default(),
RenderTargetSize::default(),
));
}
}
/// Updates textures painted by Egui.
#[cfg(feature = "render")]
#[allow(clippy::type_complexity)]
pub fn update_egui_textures_system(
mut egui_render_output: Query<
(Entity, &mut EguiRenderOutput),
Or<(With<Window>, With<EguiRenderToTextureHandle>)>,
>,
mut egui_managed_textures: ResMut<EguiManagedTextures>,
mut image_assets: ResMut<Assets<Image>>,
) {
for (entity, mut egui_render_output) in egui_render_output.iter_mut() {
let set_textures = std::mem::take(&mut egui_render_output.textures_delta.set);
for (texture_id, image_delta) in set_textures {
let color_image = egui_node::as_color_image(image_delta.image);
let texture_id = match texture_id {
egui::TextureId::Managed(texture_id) => texture_id,
egui::TextureId::User(_) => continue,
};
let sampler = ImageSampler::Descriptor(
egui_node::texture_options_as_sampler_descriptor(&image_delta.options),
);
if let Some(pos) = image_delta.pos {
// Partial update.
if let Some(managed_texture) = egui_managed_textures.get_mut(&(entity, texture_id))
{
// TODO: when bevy supports it, only update the part of the texture that changes.
update_image_rect(&mut managed_texture.color_image, pos, &color_image);
let image =
egui_node::color_image_as_bevy_image(&managed_texture.color_image, sampler);
managed_texture.handle = image_assets.add(image);
} else {
bevy_log::warn!("Partial update of a missing texture (id: {:?})", texture_id);
}
} else {
// Full update.
let image = egui_node::color_image_as_bevy_image(&color_image, sampler);
let handle = image_assets.add(image);
egui_managed_textures.insert(
(entity, texture_id),
EguiManagedTexture {
handle,
color_image,
},
);
}
}
}