Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_remote/src/lib.rs
6598 views
1
//! An implementation of the Bevy Remote Protocol, to allow for remote control of a Bevy app.
2
//!
3
//! Adding the [`RemotePlugin`] to your [`App`] will setup everything needed without
4
//! starting any transports. To start accepting remote connections you will need to
5
//! add a second plugin like the [`RemoteHttpPlugin`](http::RemoteHttpPlugin) to enable communication
6
//! over HTTP. These *remote clients* can inspect and alter the state of the
7
//! entity-component system.
8
//!
9
//! The Bevy Remote Protocol is based on the JSON-RPC 2.0 protocol.
10
//!
11
//! ## Request objects
12
//!
13
//! A typical client request might look like this:
14
//!
15
//! ```json
16
//! {
17
//! "method": "world.get_components",
18
//! "id": 0,
19
//! "params": {
20
//! "entity": 4294967298,
21
//! "components": [
22
//! "bevy_transform::components::transform::Transform"
23
//! ]
24
//! }
25
//! }
26
//! ```
27
//!
28
//! The `id` and `method` fields are required. The `params` field may be omitted
29
//! for certain methods:
30
//!
31
//! * `id` is arbitrary JSON data. The server completely ignores its contents,
32
//! and the client may use it for any purpose. It will be copied via
33
//! serialization and deserialization (so object property order, etc. can't be
34
//! relied upon to be identical) and sent back to the client as part of the
35
//! response.
36
//!
37
//! * `method` is a string that specifies one of the possible [`BrpRequest`]
38
//! variants: `world.query`, `world.get_components`, `world.insert_components`, etc. It's case-sensitive.
39
//!
40
//! * `params` is parameter data specific to the request.
41
//!
42
//! For more information, see the documentation for [`BrpRequest`].
43
//! [`BrpRequest`] is serialized to JSON via `serde`, so [the `serde`
44
//! documentation] may be useful to clarify the correspondence between the Rust
45
//! structure and the JSON format.
46
//!
47
//! ## Response objects
48
//!
49
//! A response from the server to the client might look like this:
50
//!
51
//! ```json
52
//! {
53
//! "jsonrpc": "2.0",
54
//! "id": 0,
55
//! "result": {
56
//! "bevy_transform::components::transform::Transform": {
57
//! "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 },
58
//! "scale": { "x": 1.0, "y": 1.0, "z": 1.0 },
59
//! "translation": { "x": 0.0, "y": 0.5, "z": 0.0 }
60
//! }
61
//! }
62
//! }
63
//! ```
64
//!
65
//! The `id` field will always be present. The `result` field will be present if the
66
//! request was successful. Otherwise, an `error` field will replace it.
67
//!
68
//! * `id` is the arbitrary JSON data that was sent as part of the request. It
69
//! will be identical to the `id` data sent during the request, modulo
70
//! serialization and deserialization. If there's an error reading the `id` field,
71
//! it will be `null`.
72
//!
73
//! * `result` will be present if the request succeeded and will contain the response
74
//! specific to the request.
75
//!
76
//! * `error` will be present if the request failed and will contain an error object
77
//! with more information about the cause of failure.
78
//!
79
//! ## Error objects
80
//!
81
//! An error object might look like this:
82
//!
83
//! ```json
84
//! {
85
//! "code": -32602,
86
//! "message": "Missing \"entity\" field"
87
//! }
88
//! ```
89
//!
90
//! The `code` and `message` fields will always be present. There may also be a `data` field.
91
//!
92
//! * `code` is an integer representing the kind of an error that happened. Error codes documented
93
//! in the [`error_codes`] module.
94
//!
95
//! * `message` is a short, one-sentence human-readable description of the error.
96
//!
97
//! * `data` is an optional field of arbitrary type containing additional information about the error.
98
//!
99
//! ## Built-in methods
100
//!
101
//! The Bevy Remote Protocol includes a number of built-in methods for accessing and modifying data
102
//! in the ECS.
103
//!
104
//! ### `world.get_components`
105
//!
106
//! Retrieve the values of one or more components from an entity.
107
//!
108
//! `params`:
109
//! - `entity`: The ID of the entity whose components will be fetched.
110
//! - `components`: An array of [fully-qualified type names] of components to fetch.
111
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the
112
//! components is not present or can not be reflected. Defaults to false.
113
//!
114
//! If `strict` is false:
115
//!
116
//! `result`:
117
//! - `components`: A map associating each type name to its value on the requested entity.
118
//! - `errors`: A map associating each type name with an error if it was not on the entity
119
//! or could not be reflected.
120
//!
121
//! If `strict` is true:
122
//!
123
//! `result`: A map associating each type name to its value on the requested entity.
124
//!
125
//! ### `world.query`
126
//!
127
//! Perform a query over components in the ECS, returning all matching entities and their associated
128
//! component values.
129
//!
130
//! All of the arrays that comprise this request are optional, and when they are not provided, they
131
//! will be treated as if they were empty.
132
//!
133
//! `params`:
134
//! - `data`:
135
//! - `components` (optional): An array of [fully-qualified type names] of components to fetch,
136
//! see _below_ example for a query to list all the type names in **your** project.
137
//! - `option` (optional): An array of fully-qualified type names of components to fetch optionally.
138
//! to fetch all reflectable components, you can pass in the string `"all"`.
139
//! - `has` (optional): An array of fully-qualified type names of components whose presence will be
140
//! reported as boolean values.
141
//! - `filter` (optional):
142
//! - `with` (optional): An array of fully-qualified type names of components that must be present
143
//! on entities in order for them to be included in results.
144
//! - `without` (optional): An array of fully-qualified type names of components that must *not* be
145
//! present on entities in order for them to be included in results.
146
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the components
147
//! is not present or can not be reflected. Defaults to false.
148
//!
149
//! `result`: An array, each of which is an object containing:
150
//! - `entity`: The ID of a query-matching entity.
151
//! - `components`: A map associating each type name from `components`/`option` to its value on the matching
152
//! entity if the component is present.
153
//! - `has`: A map associating each type name from `has` to a boolean value indicating whether or not the
154
//! entity has that component. If `has` was empty or omitted, this key will be omitted in the response.
155
//!
156
//! ### Example
157
//! To use the query API and retrieve Transform data for all entities that have a Transform
158
//! use this query:
159
//!
160
//! ```json
161
//! {
162
//! "jsonrpc": "2.0",
163
//! "method": "bevy/query",
164
//! "id": 0,
165
//! "params": {
166
//! "data": {
167
//! "components": ["bevy_transform::components::transform::Transform"]
168
//! "option": [],
169
//! "has": []
170
//! },
171
//! "filter": {
172
//! "with": [],
173
//! "without": []
174
//! },
175
//! "strict": false
176
//! }
177
//! }
178
//! ```
179
//!
180
//!
181
//! To query all entities and all of their Reflectable components (and retrieve their values), you can pass in "all" for the option field:
182
//! ```json
183
//! {
184
//! "jsonrpc": "2.0",
185
//! "method": "bevy/query",
186
//! "id": 0,
187
//! "params": {
188
//! "data": {
189
//! "components": []
190
//! "option": "all",
191
//! "has": []
192
//! },
193
//! "filter": {
194
//! "with": [],
195
//! "without": []
196
//! },
197
//! "strict": false
198
//! }
199
//! }
200
//! ```
201
//!
202
//! This should return you something like the below (in a larger list):
203
//! ```json
204
//! {
205
//! "components": {
206
//! "bevy_camera::Camera3d": {
207
//! "depth_load_op": {
208
//! "Clear": 0.0
209
//! },
210
//! "depth_texture_usages": 16,
211
//! "screen_space_specular_transmission_quality": "Medium",
212
//! "screen_space_specular_transmission_steps": 1
213
//! },
214
//! "bevy_core_pipeline::tonemapping::DebandDither": "Enabled",
215
//! "bevy_core_pipeline::tonemapping::Tonemapping": "TonyMcMapface",
216
//! "bevy_light::cluster::ClusterConfig": {
217
//! "FixedZ": {
218
//! "dynamic_resizing": true,
219
//! "total": 4096,
220
//! "z_config": {
221
//! "far_z_mode": "MaxClusterableObjectRange",
222
//! "first_slice_depth": 5.0
223
//! },
224
//! "z_slices": 24
225
//! }
226
//! },
227
//! "bevy_camera::Camera": {
228
//! "clear_color": "Default",
229
//! "is_active": true,
230
//! "msaa_writeback": true,
231
//! "order": 0,
232
//! "sub_camera_view": null,
233
//! "target": {
234
//! "Window": "Primary"
235
//! },
236
//! "viewport": null
237
//! },
238
//! "bevy_camera::Projection": {
239
//! "Perspective": {
240
//! "aspect_ratio": 1.7777777910232544,
241
//! "far": 1000.0,
242
//! "fov": 0.7853981852531433,
243
//! "near": 0.10000000149011612
244
//! }
245
//! },
246
//! "bevy_camera::primitives::Frustum": {},
247
//! "bevy_render::sync_world::RenderEntity": 4294967291,
248
//! "bevy_render::sync_world::SyncToRenderWorld": {},
249
//! "bevy_render::view::Msaa": "Sample4",
250
//! "bevy_camera::visibility::InheritedVisibility": true,
251
//! "bevy_camera::visibility::ViewVisibility": false,
252
//! "bevy_camera::visibility::Visibility": "Inherited",
253
//! "bevy_camera::visibility::VisibleEntities": {},
254
//! "bevy_transform::components::global_transform::GlobalTransform": [
255
//! 0.9635179042816162,
256
//! -3.725290298461914e-9,
257
//! 0.26764383912086487,
258
//! 0.11616238951683044,
259
//! 0.9009039402008056,
260
//! -0.4181846082210541,
261
//! -0.24112138152122495,
262
//! 0.4340185225009918,
263
//! 0.8680371046066284,
264
//! -2.5,
265
//! 4.5,
266
//! 9.0
267
//! ],
268
//! "bevy_transform::components::transform::Transform": {
269
//! "rotation": [
270
//! -0.22055435180664065,
271
//! -0.13167093694210052,
272
//! -0.03006339818239212,
273
//! 0.9659786224365234
274
//! ],
275
//! "scale": [
276
//! 1.0,
277
//! 1.0,
278
//! 1.0
279
//! ],
280
//! "translation": [
281
//! -2.5,
282
//! 4.5,
283
//! 9.0
284
//! ]
285
//! },
286
//! "bevy_transform::components::transform::TransformTreeChanged": null
287
//! },
288
//! "entity": 4294967261
289
//!},
290
//! ```
291
//!
292
//! ### `world.spawn_entity`
293
//!
294
//! Create a new entity with the provided components and return the resulting entity ID.
295
//!
296
//! `params`:
297
//! - `components`: A map associating each component's [fully-qualified type name] with its value.
298
//!
299
//! `result`:
300
//! - `entity`: The ID of the newly spawned entity.
301
//!
302
//! ### `world.despawn_entity`
303
//!
304
//! Despawn the entity with the given ID.
305
//!
306
//! `params`:
307
//! - `entity`: The ID of the entity to be despawned.
308
//!
309
//! `result`: null.
310
//!
311
//! ### `world.remove_components`
312
//!
313
//! Delete one or more components from an entity.
314
//!
315
//! `params`:
316
//! - `entity`: The ID of the entity whose components should be removed.
317
//! - `components`: An array of [fully-qualified type names] of components to be removed.
318
//!
319
//! `result`: null.
320
//!
321
//! ### `world.insert_components`
322
//!
323
//! Insert one or more components into an entity.
324
//!
325
//! `params`:
326
//! - `entity`: The ID of the entity to insert components into.
327
//! - `components`: A map associating each component's fully-qualified type name with its value.
328
//!
329
//! `result`: null.
330
//!
331
//! ### `world.mutate_components`
332
//!
333
//! Mutate a field in a component.
334
//!
335
//! `params`:
336
//! - `entity`: The ID of the entity with the component to mutate.
337
//! - `component`: The component's [fully-qualified type name].
338
//! - `path`: The path of the field within the component. See
339
//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.
340
//! - `value`: The value to insert at `path`.
341
//!
342
//! `result`: null.
343
//!
344
//! ### `world.reparent_entities`
345
//!
346
//! Assign a new parent to one or more entities.
347
//!
348
//! `params`:
349
//! - `entities`: An array of entity IDs of entities that will be made children of the `parent`.
350
//! - `parent` (optional): The entity ID of the parent to which the child entities will be assigned.
351
//! If excluded, the given entities will be removed from their parents.
352
//!
353
//! `result`: null.
354
//!
355
//! ### `world.list_components`
356
//!
357
//! List all registered components or all components present on an entity.
358
//!
359
//! When `params` is not provided, this lists all registered components. If `params` is provided,
360
//! this lists only those components present on the provided entity.
361
//!
362
//! `params` (optional):
363
//! - `entity`: The ID of the entity whose components will be listed.
364
//!
365
//! `result`: An array of fully-qualified type names of components.
366
//!
367
//! ### `world.get_components+watch`
368
//!
369
//! Watch the values of one or more components from an entity.
370
//!
371
//! `params`:
372
//! - `entity`: The ID of the entity whose components will be fetched.
373
//! - `components`: An array of [fully-qualified type names] of components to fetch.
374
//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the
375
//! components is not present or can not be reflected. Defaults to false.
376
//!
377
//! If `strict` is false:
378
//!
379
//! `result`:
380
//! - `components`: A map of components added or changed in the last tick associating each type
381
//! name to its value on the requested entity.
382
//! - `removed`: An array of fully-qualified type names of components removed from the entity
383
//! in the last tick.
384
//! - `errors`: A map associating each type name with an error if it was not on the entity
385
//! or could not be reflected.
386
//!
387
//! If `strict` is true:
388
//!
389
//! `result`:
390
//! - `components`: A map of components added or changed in the last tick associating each type
391
//! name to its value on the requested entity.
392
//! - `removed`: An array of fully-qualified type names of components removed from the entity
393
//! in the last tick.
394
//!
395
//! ### `world.list_components+watch`
396
//!
397
//! Watch all components present on an entity.
398
//!
399
//! When `params` is not provided, this lists all registered components. If `params` is provided,
400
//! this lists only those components present on the provided entity.
401
//!
402
//! `params`:
403
//! - `entity`: The ID of the entity whose components will be listed.
404
//!
405
//! `result`:
406
//! - `added`: An array of fully-qualified type names of components added to the entity in the
407
//! last tick.
408
//! - `removed`: An array of fully-qualified type names of components removed from the entity
409
//! in the last tick.
410
//!
411
//! ### `world.get_resources`
412
//!
413
//! Extract the value of a given resource from the world.
414
//!
415
//! `params`:
416
//! - `resource`: The [fully-qualified type name] of the resource to get.
417
//!
418
//! `result`:
419
//! - `value`: The value of the resource in the world.
420
//!
421
//! ### `world.insert_resources`
422
//!
423
//! Insert the given resource into the world with the given value.
424
//!
425
//! `params`:
426
//! - `resource`: The [fully-qualified type name] of the resource to insert.
427
//! - `value`: The value of the resource to be inserted.
428
//!
429
//! `result`: null.
430
//!
431
//! ### `world.remove_resources`
432
//!
433
//! Remove the given resource from the world.
434
//!
435
//! `params`
436
//! - `resource`: The [fully-qualified type name] of the resource to remove.
437
//!
438
//! `result`: null.
439
//!
440
//! ### `world.mutate_resources`
441
//!
442
//! Mutate a field in a resource.
443
//!
444
//! `params`:
445
//! - `resource`: The [fully-qualified type name] of the resource to mutate.
446
//! - `path`: The path of the field within the resource. See
447
//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.
448
//! - `value`: The value to be inserted at `path`.
449
//!
450
//! `result`: null.
451
//!
452
//! ### `world.list_resources`
453
//!
454
//! List all reflectable registered resource types. This method has no parameters.
455
//!
456
//! `result`: An array of [fully-qualified type names] of registered resource types.
457
//!
458
//! ## Custom methods
459
//!
460
//! In addition to the provided methods, the Bevy Remote Protocol can be extended to include custom
461
//! methods. This is primarily done during the initialization of [`RemotePlugin`], although the
462
//! methods may also be extended at runtime using the [`RemoteMethods`] resource.
463
//!
464
//! ### Example
465
//! ```ignore
466
//! fn main() {
467
//! App::new()
468
//! .add_plugins(DefaultPlugins)
469
//! .add_plugins(
470
//! // `default` adds all of the built-in methods, while `with_method` extends them
471
//! RemotePlugin::default()
472
//! .with_method("super_user/cool_method", path::to::my::cool::handler)
473
//! // ... more methods can be added by chaining `with_method`
474
//! )
475
//! .add_systems(
476
//! // ... standard application setup
477
//! )
478
//! .run();
479
//! }
480
//! ```
481
//!
482
//! The handler is expected to be a system-convertible function which takes optional JSON parameters
483
//! as input and returns a [`BrpResult`]. This means that it should have a type signature which looks
484
//! something like this:
485
//! ```
486
//! # use serde_json::Value;
487
//! # use bevy_ecs::prelude::{In, World};
488
//! # use bevy_remote::BrpResult;
489
//! fn handler(In(params): In<Option<Value>>, world: &mut World) -> BrpResult {
490
//! todo!()
491
//! }
492
//! ```
493
//!
494
//! Arbitrary system parameters can be used in conjunction with the optional `Value` input. The
495
//! handler system will always run with exclusive `World` access.
496
//!
497
//! [the `serde` documentation]: https://serde.rs/
498
//! [fully-qualified type names]: bevy_reflect::TypePath::type_path
499
//! [fully-qualified type name]: bevy_reflect::TypePath::type_path
500
501
extern crate alloc;
502
503
use async_channel::{Receiver, Sender};
504
use bevy_app::{prelude::*, MainScheduleOrder};
505
use bevy_derive::{Deref, DerefMut};
506
use bevy_ecs::{
507
entity::Entity,
508
resource::Resource,
509
schedule::{IntoScheduleConfigs, ScheduleLabel, SystemSet},
510
system::{Commands, In, IntoSystem, ResMut, System, SystemId},
511
world::World,
512
};
513
use bevy_platform::collections::HashMap;
514
use bevy_utils::prelude::default;
515
use serde::{Deserialize, Serialize};
516
use serde_json::Value;
517
use std::sync::RwLock;
518
519
pub mod builtin_methods;
520
#[cfg(feature = "http")]
521
pub mod http;
522
pub mod schemas;
523
524
const CHANNEL_SIZE: usize = 16;
525
526
/// Add this plugin to your [`App`] to allow remote connections to inspect and modify entities.
527
///
528
/// This the main plugin for `bevy_remote`. See the [crate-level documentation] for details on
529
/// the available protocols and its default methods.
530
///
531
/// [crate-level documentation]: crate
532
pub struct RemotePlugin {
533
/// The verbs that the server will recognize and respond to.
534
methods: RwLock<Vec<(String, RemoteMethodHandler)>>,
535
}
536
537
impl RemotePlugin {
538
/// Create a [`RemotePlugin`] with the default address and port but without
539
/// any associated methods.
540
fn empty() -> Self {
541
Self {
542
methods: RwLock::new(vec![]),
543
}
544
}
545
546
/// Add a remote method to the plugin using the given `name` and `handler`.
547
#[must_use]
548
pub fn with_method<M>(
549
mut self,
550
name: impl Into<String>,
551
handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,
552
) -> Self {
553
self.methods.get_mut().unwrap().push((
554
name.into(),
555
RemoteMethodHandler::Instant(Box::new(IntoSystem::into_system(handler))),
556
));
557
self
558
}
559
560
/// Add a remote method with a watching handler to the plugin using the given `name`.
561
#[must_use]
562
pub fn with_watching_method<M>(
563
mut self,
564
name: impl Into<String>,
565
handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,
566
) -> Self {
567
self.methods.get_mut().unwrap().push((
568
name.into(),
569
RemoteMethodHandler::Watching(Box::new(IntoSystem::into_system(handler))),
570
));
571
self
572
}
573
}
574
575
impl Default for RemotePlugin {
576
fn default() -> Self {
577
Self::empty()
578
.with_method(
579
builtin_methods::BRP_GET_COMPONENTS_METHOD,
580
builtin_methods::process_remote_get_components_request,
581
)
582
.with_method(
583
builtin_methods::BRP_QUERY_METHOD,
584
builtin_methods::process_remote_query_request,
585
)
586
.with_method(
587
builtin_methods::BRP_SPAWN_ENTITY_METHOD,
588
builtin_methods::process_remote_spawn_entity_request,
589
)
590
.with_method(
591
builtin_methods::BRP_INSERT_COMPONENTS_METHOD,
592
builtin_methods::process_remote_insert_components_request,
593
)
594
.with_method(
595
builtin_methods::BRP_REMOVE_COMPONENTS_METHOD,
596
builtin_methods::process_remote_remove_components_request,
597
)
598
.with_method(
599
builtin_methods::BRP_DESPAWN_COMPONENTS_METHOD,
600
builtin_methods::process_remote_despawn_entity_request,
601
)
602
.with_method(
603
builtin_methods::BRP_REPARENT_ENTITIES_METHOD,
604
builtin_methods::process_remote_reparent_entities_request,
605
)
606
.with_method(
607
builtin_methods::BRP_LIST_COMPONENTS_METHOD,
608
builtin_methods::process_remote_list_components_request,
609
)
610
.with_method(
611
builtin_methods::BRP_MUTATE_COMPONENTS_METHOD,
612
builtin_methods::process_remote_mutate_components_request,
613
)
614
.with_method(
615
builtin_methods::RPC_DISCOVER_METHOD,
616
builtin_methods::process_remote_list_methods_request,
617
)
618
.with_watching_method(
619
builtin_methods::BRP_GET_COMPONENTS_AND_WATCH_METHOD,
620
builtin_methods::process_remote_get_components_watching_request,
621
)
622
.with_watching_method(
623
builtin_methods::BRP_LIST_COMPONENTS_AND_WATCH_METHOD,
624
builtin_methods::process_remote_list_components_watching_request,
625
)
626
.with_method(
627
builtin_methods::BRP_GET_RESOURCE_METHOD,
628
builtin_methods::process_remote_get_resources_request,
629
)
630
.with_method(
631
builtin_methods::BRP_INSERT_RESOURCE_METHOD,
632
builtin_methods::process_remote_insert_resources_request,
633
)
634
.with_method(
635
builtin_methods::BRP_REMOVE_RESOURCE_METHOD,
636
builtin_methods::process_remote_remove_resources_request,
637
)
638
.with_method(
639
builtin_methods::BRP_MUTATE_RESOURCE_METHOD,
640
builtin_methods::process_remote_mutate_resources_request,
641
)
642
.with_method(
643
builtin_methods::BRP_LIST_RESOURCES_METHOD,
644
builtin_methods::process_remote_list_resources_request,
645
)
646
.with_method(
647
builtin_methods::BRP_REGISTRY_SCHEMA_METHOD,
648
builtin_methods::export_registry_types,
649
)
650
}
651
}
652
653
impl Plugin for RemotePlugin {
654
fn build(&self, app: &mut App) {
655
let mut remote_methods = RemoteMethods::new();
656
657
let plugin_methods = &mut *self.methods.write().unwrap();
658
for (name, handler) in plugin_methods.drain(..) {
659
remote_methods.insert(
660
name,
661
match handler {
662
RemoteMethodHandler::Instant(system) => RemoteMethodSystemId::Instant(
663
app.main_mut().world_mut().register_boxed_system(system),
664
),
665
RemoteMethodHandler::Watching(system) => RemoteMethodSystemId::Watching(
666
app.main_mut().world_mut().register_boxed_system(system),
667
),
668
},
669
);
670
}
671
672
app.init_schedule(RemoteLast)
673
.world_mut()
674
.resource_mut::<MainScheduleOrder>()
675
.insert_after(Last, RemoteLast);
676
677
app.insert_resource(remote_methods)
678
.init_resource::<schemas::SchemaTypesMetadata>()
679
.init_resource::<RemoteWatchingRequests>()
680
.add_systems(PreStartup, setup_mailbox_channel)
681
.configure_sets(
682
RemoteLast,
683
(RemoteSystems::ProcessRequests, RemoteSystems::Cleanup).chain(),
684
)
685
.add_systems(
686
RemoteLast,
687
(
688
(process_remote_requests, process_ongoing_watching_requests)
689
.chain()
690
.in_set(RemoteSystems::ProcessRequests),
691
remove_closed_watching_requests.in_set(RemoteSystems::Cleanup),
692
),
693
);
694
}
695
}
696
697
/// Schedule that contains all systems to process Bevy Remote Protocol requests
698
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
699
pub struct RemoteLast;
700
701
/// The systems sets of the [`RemoteLast`] schedule.
702
///
703
/// These can be useful for ordering.
704
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
705
pub enum RemoteSystems {
706
/// Processing of remote requests.
707
ProcessRequests,
708
/// Cleanup (remove closed watchers etc)
709
Cleanup,
710
}
711
712
/// Deprecated alias for [`RemoteSystems`].
713
#[deprecated(since = "0.17.0", note = "Renamed to `RemoteSystems`.")]
714
pub type RemoteSet = RemoteSystems;
715
716
/// A type to hold the allowed types of systems to be used as method handlers.
717
#[derive(Debug)]
718
pub enum RemoteMethodHandler {
719
/// A handler that only runs once and returns one response.
720
Instant(Box<dyn System<In = In<Option<Value>>, Out = BrpResult>>),
721
/// A handler that watches for changes and response when a change is detected.
722
Watching(Box<dyn System<In = In<Option<Value>>, Out = BrpResult<Option<Value>>>>),
723
}
724
725
/// The [`SystemId`] of a function that implements a remote instant method (`world.get_components`, `world.query`, etc.)
726
///
727
/// The first parameter is the JSON value of the `params`. Typically, an
728
/// implementation will deserialize these as the first thing they do.
729
///
730
/// The returned JSON value will be returned as the response. Bevy will
731
/// automatically populate the `id` field before sending.
732
pub type RemoteInstantMethodSystemId = SystemId<In<Option<Value>>, BrpResult>;
733
734
/// The [`SystemId`] of a function that implements a remote watching method (`world.get_components+watch`, `world.list_components+watch`, etc.)
735
///
736
/// The first parameter is the JSON value of the `params`. Typically, an
737
/// implementation will deserialize these as the first thing they do.
738
///
739
/// The optional returned JSON value will be sent as a response. If no
740
/// changes were detected this should be [`None`]. Re-running of this
741
/// handler is done in the [`RemotePlugin`].
742
pub type RemoteWatchingMethodSystemId = SystemId<In<Option<Value>>, BrpResult<Option<Value>>>;
743
744
/// The [`SystemId`] of a function that can be used as a remote method.
745
#[derive(Debug, Clone, Copy)]
746
pub enum RemoteMethodSystemId {
747
/// A handler that only runs once and returns one response.
748
Instant(RemoteInstantMethodSystemId),
749
/// A handler that watches for changes and response when a change is detected.
750
Watching(RemoteWatchingMethodSystemId),
751
}
752
753
/// Holds all implementations of methods known to the server.
754
///
755
/// Custom methods can be added to this list using [`RemoteMethods::insert`].
756
#[derive(Debug, Resource, Default)]
757
pub struct RemoteMethods(HashMap<String, RemoteMethodSystemId>);
758
759
impl RemoteMethods {
760
/// Creates a new [`RemoteMethods`] resource with no methods registered in it.
761
pub fn new() -> Self {
762
default()
763
}
764
765
/// Adds a new method, replacing any existing method with that name.
766
///
767
/// If there was an existing method with that name, returns its handler.
768
pub fn insert(
769
&mut self,
770
method_name: impl Into<String>,
771
handler: RemoteMethodSystemId,
772
) -> Option<RemoteMethodSystemId> {
773
self.0.insert(method_name.into(), handler)
774
}
775
776
/// Get a [`RemoteMethodSystemId`] with its method name.
777
pub fn get(&self, method: &str) -> Option<&RemoteMethodSystemId> {
778
self.0.get(method)
779
}
780
781
/// Get a [`Vec<String>`] with method names.
782
pub fn methods(&self) -> Vec<String> {
783
self.0.keys().cloned().collect()
784
}
785
}
786
787
/// Holds the [`BrpMessage`]'s of all ongoing watching requests along with their handlers.
788
#[derive(Debug, Resource, Default)]
789
pub struct RemoteWatchingRequests(Vec<(BrpMessage, RemoteWatchingMethodSystemId)>);
790
791
/// A single request from a Bevy Remote Protocol client to the server,
792
/// serialized in JSON.
793
///
794
/// The JSON payload is expected to look like this:
795
///
796
/// ```json
797
/// {
798
/// "jsonrpc": "2.0",
799
/// "method": "world.get_components",
800
/// "id": 0,
801
/// "params": {
802
/// "entity": 4294967298,
803
/// "components": [
804
/// "bevy_transform::components::transform::Transform"
805
/// ]
806
/// }
807
/// }
808
/// ```
809
/// Or, to list all the fully-qualified type paths in **your** project, pass Null to the
810
/// `params`.
811
/// ```json
812
/// {
813
/// "jsonrpc": "2.0",
814
/// "method": "world.list_components",
815
/// "id": 0,
816
/// "params": null
817
///}
818
///```
819
///
820
/// In Rust:
821
/// ```ignore
822
/// let req = BrpRequest {
823
/// jsonrpc: "2.0".to_string(),
824
/// method: BRP_LIST_METHOD.to_string(), // All the methods have consts
825
/// id: Some(ureq::json!(0)),
826
/// params: None,
827
/// };
828
/// ```
829
#[derive(Debug, Serialize, Deserialize, Clone)]
830
pub struct BrpRequest {
831
/// This field is mandatory and must be set to `"2.0"` for the request to be accepted.
832
pub jsonrpc: String,
833
834
/// The action to be performed.
835
pub method: String,
836
837
/// Arbitrary data that will be returned verbatim to the client as part of
838
/// the response.
839
#[serde(skip_serializing_if = "Option::is_none")]
840
pub id: Option<Value>,
841
842
/// The parameters, specific to each method.
843
///
844
/// These are passed as the first argument to the method handler.
845
/// Sometimes params can be omitted.
846
#[serde(skip_serializing_if = "Option::is_none")]
847
pub params: Option<Value>,
848
}
849
850
/// A response according to BRP.
851
#[derive(Debug, Serialize, Deserialize, Clone)]
852
pub struct BrpResponse {
853
/// This field is mandatory and must be set to `"2.0"`.
854
pub jsonrpc: &'static str,
855
856
/// The id of the original request.
857
pub id: Option<Value>,
858
859
/// The actual response payload.
860
#[serde(flatten)]
861
pub payload: BrpPayload,
862
}
863
864
impl BrpResponse {
865
/// Generates a [`BrpResponse`] from an id and a `Result`.
866
#[must_use]
867
pub fn new(id: Option<Value>, result: BrpResult) -> Self {
868
Self {
869
jsonrpc: "2.0",
870
id,
871
payload: BrpPayload::from(result),
872
}
873
}
874
}
875
876
/// A result/error payload present in every response.
877
#[derive(Debug, Serialize, Deserialize, Clone)]
878
#[serde(rename_all = "snake_case")]
879
pub enum BrpPayload {
880
/// `Ok` variant
881
Result(Value),
882
/// `Err` variant
883
Error(BrpError),
884
}
885
886
impl From<BrpResult> for BrpPayload {
887
fn from(value: BrpResult) -> Self {
888
match value {
889
Ok(v) => Self::Result(v),
890
Err(err) => Self::Error(err),
891
}
892
}
893
}
894
895
/// An error a request might return.
896
#[derive(Debug, Serialize, Deserialize, Clone)]
897
pub struct BrpError {
898
/// Defines the general type of the error.
899
pub code: i16,
900
/// Short, human-readable description of the error.
901
pub message: String,
902
/// Optional additional error data.
903
#[serde(skip_serializing_if = "Option::is_none")]
904
pub data: Option<Value>,
905
}
906
907
impl BrpError {
908
/// Entity wasn't found.
909
#[must_use]
910
pub fn entity_not_found(entity: Entity) -> Self {
911
Self {
912
code: error_codes::ENTITY_NOT_FOUND,
913
message: format!("Entity {entity} not found"),
914
data: None,
915
}
916
}
917
918
/// Component wasn't found in an entity.
919
#[must_use]
920
pub fn component_not_present(component: &str, entity: Entity) -> Self {
921
Self {
922
code: error_codes::COMPONENT_NOT_PRESENT,
923
message: format!("Component `{component}` not present in Entity {entity}"),
924
data: None,
925
}
926
}
927
928
/// An arbitrary component error. Possibly related to reflection.
929
#[must_use]
930
pub fn component_error<E: ToString>(error: E) -> Self {
931
Self {
932
code: error_codes::COMPONENT_ERROR,
933
message: error.to_string(),
934
data: None,
935
}
936
}
937
938
/// Resource was not present in the world.
939
#[must_use]
940
pub fn resource_not_present(resource: &str) -> Self {
941
Self {
942
code: error_codes::RESOURCE_NOT_PRESENT,
943
message: format!("Resource `{resource}` not present in the world"),
944
data: None,
945
}
946
}
947
948
/// An arbitrary resource error. Possibly related to reflection.
949
#[must_use]
950
pub fn resource_error<E: ToString>(error: E) -> Self {
951
Self {
952
code: error_codes::RESOURCE_ERROR,
953
message: error.to_string(),
954
data: None,
955
}
956
}
957
958
/// An arbitrary internal error.
959
#[must_use]
960
pub fn internal<E: ToString>(error: E) -> Self {
961
Self {
962
code: error_codes::INTERNAL_ERROR,
963
message: error.to_string(),
964
data: None,
965
}
966
}
967
968
/// Attempt to reparent an entity to itself.
969
#[must_use]
970
pub fn self_reparent(entity: Entity) -> Self {
971
Self {
972
code: error_codes::SELF_REPARENT,
973
message: format!("Cannot reparent Entity {entity} to itself"),
974
data: None,
975
}
976
}
977
}
978
979
/// Error codes used by BRP.
980
pub mod error_codes {
981
// JSON-RPC errors
982
// Note that the range -32728 to -32000 (inclusive) is reserved by the JSON-RPC specification.
983
984
/// Invalid JSON.
985
pub const PARSE_ERROR: i16 = -32700;
986
987
/// JSON sent is not a valid request object.
988
pub const INVALID_REQUEST: i16 = -32600;
989
990
/// The method does not exist / is not available.
991
pub const METHOD_NOT_FOUND: i16 = -32601;
992
993
/// Invalid method parameter(s).
994
pub const INVALID_PARAMS: i16 = -32602;
995
996
/// Internal error.
997
pub const INTERNAL_ERROR: i16 = -32603;
998
999
// Bevy errors (i.e. application errors)
1000
1001
/// Entity not found.
1002
pub const ENTITY_NOT_FOUND: i16 = -23401;
1003
1004
/// Could not reflect or find component.
1005
pub const COMPONENT_ERROR: i16 = -23402;
1006
1007
/// Could not find component in entity.
1008
pub const COMPONENT_NOT_PRESENT: i16 = -23403;
1009
1010
/// Cannot reparent an entity to itself.
1011
pub const SELF_REPARENT: i16 = -23404;
1012
1013
/// Could not reflect or find resource.
1014
pub const RESOURCE_ERROR: i16 = -23501;
1015
1016
/// Could not find resource in the world.
1017
pub const RESOURCE_NOT_PRESENT: i16 = -23502;
1018
}
1019
1020
/// The result of a request.
1021
pub type BrpResult<T = Value> = Result<T, BrpError>;
1022
1023
/// The requests may occur on their own or in batches.
1024
/// Actual parsing is deferred for the sake of proper
1025
/// error reporting.
1026
#[derive(Debug, Clone, Serialize, Deserialize)]
1027
#[serde(untagged)]
1028
pub enum BrpBatch {
1029
/// Multiple requests with deferred parsing.
1030
Batch(Vec<Value>),
1031
/// A single request with deferred parsing.
1032
Single(Value),
1033
}
1034
1035
/// A message from the Bevy Remote Protocol server thread to the main world.
1036
///
1037
/// This is placed in the [`BrpReceiver`].
1038
#[derive(Debug, Clone)]
1039
pub struct BrpMessage {
1040
/// The request method.
1041
pub method: String,
1042
1043
/// The request params.
1044
pub params: Option<Value>,
1045
1046
/// The channel on which the response is to be sent.
1047
///
1048
/// The value sent here is serialized and sent back to the client.
1049
pub sender: Sender<BrpResult>,
1050
}
1051
1052
/// A resource holding the matching sender for the [`BrpReceiver`]'s receiver.
1053
#[derive(Debug, Resource, Deref, DerefMut)]
1054
pub struct BrpSender(Sender<BrpMessage>);
1055
1056
/// A resource that receives messages sent by Bevy Remote Protocol clients.
1057
///
1058
/// Every frame, the `process_remote_requests` system drains this mailbox and
1059
/// processes the messages within.
1060
#[derive(Debug, Resource, Deref, DerefMut)]
1061
pub struct BrpReceiver(Receiver<BrpMessage>);
1062
1063
fn setup_mailbox_channel(mut commands: Commands) {
1064
// Create the channel and the mailbox.
1065
let (request_sender, request_receiver) = async_channel::bounded(CHANNEL_SIZE);
1066
commands.insert_resource(BrpSender(request_sender));
1067
commands.insert_resource(BrpReceiver(request_receiver));
1068
}
1069
1070
/// A system that receives requests placed in the [`BrpReceiver`] and processes
1071
/// them, using the [`RemoteMethods`] resource to map each request to its handler.
1072
///
1073
/// This needs exclusive access to the [`World`] because clients can manipulate
1074
/// anything in the ECS.
1075
fn process_remote_requests(world: &mut World) {
1076
if !world.contains_resource::<BrpReceiver>() {
1077
return;
1078
}
1079
1080
while let Ok(message) = world.resource_mut::<BrpReceiver>().try_recv() {
1081
// Fetch the handler for the method. If there's no such handler
1082
// registered, return an error.
1083
let Some(&handler) = world.resource::<RemoteMethods>().get(&message.method) else {
1084
let _ = message.sender.force_send(Err(BrpError {
1085
code: error_codes::METHOD_NOT_FOUND,
1086
message: format!("Method `{}` not found", message.method),
1087
data: None,
1088
}));
1089
return;
1090
};
1091
1092
match handler {
1093
RemoteMethodSystemId::Instant(id) => {
1094
let result = match world.run_system_with(id, message.params) {
1095
Ok(result) => result,
1096
Err(error) => {
1097
let _ = message.sender.force_send(Err(BrpError {
1098
code: error_codes::INTERNAL_ERROR,
1099
message: format!("Failed to run method handler: {error}"),
1100
data: None,
1101
}));
1102
continue;
1103
}
1104
};
1105
1106
let _ = message.sender.force_send(result);
1107
}
1108
RemoteMethodSystemId::Watching(id) => {
1109
world
1110
.resource_mut::<RemoteWatchingRequests>()
1111
.0
1112
.push((message, id));
1113
}
1114
}
1115
}
1116
}
1117
1118
/// A system that checks all ongoing watching requests for changes that should be sent
1119
/// and handles it if so.
1120
fn process_ongoing_watching_requests(world: &mut World) {
1121
world.resource_scope::<RemoteWatchingRequests, ()>(|world, requests| {
1122
for (message, system_id) in requests.0.iter() {
1123
let handler_result = process_single_ongoing_watching_request(world, message, system_id);
1124
let sender_result = match handler_result {
1125
Ok(Some(value)) => message.sender.try_send(Ok(value)),
1126
Err(err) => message.sender.try_send(Err(err)),
1127
Ok(None) => continue,
1128
};
1129
1130
if sender_result.is_err() {
1131
// The [`remove_closed_watching_requests`] system will clean this up.
1132
message.sender.close();
1133
}
1134
}
1135
});
1136
}
1137
1138
fn process_single_ongoing_watching_request(
1139
world: &mut World,
1140
message: &BrpMessage,
1141
system_id: &RemoteWatchingMethodSystemId,
1142
) -> BrpResult<Option<Value>> {
1143
world
1144
.run_system_with(*system_id, message.params.clone())
1145
.map_err(|error| BrpError {
1146
code: error_codes::INTERNAL_ERROR,
1147
message: format!("Failed to run method handler: {error}"),
1148
data: None,
1149
})?
1150
}
1151
1152
fn remove_closed_watching_requests(mut requests: ResMut<RemoteWatchingRequests>) {
1153
for i in (0..requests.0.len()).rev() {
1154
let Some((message, _)) = requests.0.get(i) else {
1155
unreachable!()
1156
};
1157
1158
if message.sender.is_closed() {
1159
requests.0.swap_remove(i);
1160
}
1161
}
1162
}
1163
1164