Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_remote/src/lib.rs
6849 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
//! ### `registry.schema`
459
//!
460
//! Retrieve schema information about registered types in the Bevy app's type registry.
461
//!
462
//! `params` (optional):
463
//! - `with_crates`: An array of crate names to include in the results. When empty or omitted, types from all crates will be included.
464
//! - `without_crates`: An array of crate names to exclude from the results. When empty or omitted, no crates will be excluded.
465
//! - `type_limit`: Additional type constraints:
466
//! - `with`: An array of [fully-qualified type names] that must be present for a type to be included
467
//! - `without`: An array of [fully-qualified type names] that must not be present for a type to be excluded
468
//!
469
//! `result`: A map associating each type's [fully-qualified type name] to a [`JsonSchemaBevyType`](crate::schemas::json_schema::JsonSchemaBevyType).
470
//! This contains schema information about that type, including field definitions, type information, reflect type information, and other metadata
471
//! helpful for understanding the structure of the type.
472
//!
473
//! ### `rpc.discover`
474
//!
475
//! Discover available remote methods and server information. This follows the [`OpenRPC` specification for service discovery](https://spec.open-rpc.org/#service-discovery-method).
476
//!
477
//! This method takes no parameters.
478
//!
479
//! `result`: An `OpenRPC` document containing:
480
//! - Information about all available remote methods
481
//! - Server connection information (when using HTTP transport)
482
//! - `OpenRPC` specification version
483
//!
484
//! ## Custom methods
485
//!
486
//! In addition to the provided methods, the Bevy Remote Protocol can be extended to include custom
487
//! methods. This is primarily done during the initialization of [`RemotePlugin`], although the
488
//! methods may also be extended at runtime using the [`RemoteMethods`] resource.
489
//!
490
//! ### Example
491
//! ```ignore
492
//! fn main() {
493
//! App::new()
494
//! .add_plugins(DefaultPlugins)
495
//! .add_plugins(
496
//! // `default` adds all of the built-in methods, while `with_method` extends them
497
//! RemotePlugin::default()
498
//! .with_method("super_user/cool_method", path::to::my::cool::handler)
499
//! // ... more methods can be added by chaining `with_method`
500
//! )
501
//! .add_systems(
502
//! // ... standard application setup
503
//! )
504
//! .run();
505
//! }
506
//! ```
507
//!
508
//! The handler is expected to be a system-convertible function which takes optional JSON parameters
509
//! as input and returns a [`BrpResult`]. This means that it should have a type signature which looks
510
//! something like this:
511
//! ```
512
//! # use serde_json::Value;
513
//! # use bevy_ecs::prelude::{In, World};
514
//! # use bevy_remote::BrpResult;
515
//! fn handler(In(params): In<Option<Value>>, world: &mut World) -> BrpResult {
516
//! todo!()
517
//! }
518
//! ```
519
//!
520
//! Arbitrary system parameters can be used in conjunction with the optional `Value` input. The
521
//! handler system will always run with exclusive `World` access.
522
//!
523
//! [the `serde` documentation]: https://serde.rs/
524
//! [fully-qualified type names]: bevy_reflect::TypePath::type_path
525
//! [fully-qualified type name]: bevy_reflect::TypePath::type_path
526
527
extern crate alloc;
528
529
use async_channel::{Receiver, Sender};
530
use bevy_app::{prelude::*, MainScheduleOrder};
531
use bevy_derive::{Deref, DerefMut};
532
use bevy_ecs::{
533
entity::Entity,
534
resource::Resource,
535
schedule::{IntoScheduleConfigs, ScheduleLabel, SystemSet},
536
system::{Commands, In, IntoSystem, ResMut, System, SystemId},
537
world::World,
538
};
539
use bevy_platform::collections::HashMap;
540
use bevy_utils::prelude::default;
541
use serde::{Deserialize, Serialize};
542
use serde_json::Value;
543
use std::sync::RwLock;
544
545
pub mod builtin_methods;
546
#[cfg(feature = "http")]
547
pub mod http;
548
pub mod schemas;
549
550
const CHANNEL_SIZE: usize = 16;
551
552
/// Add this plugin to your [`App`] to allow remote connections to inspect and modify entities.
553
///
554
/// This the main plugin for `bevy_remote`. See the [crate-level documentation] for details on
555
/// the available protocols and its default methods.
556
///
557
/// [crate-level documentation]: crate
558
pub struct RemotePlugin {
559
/// The verbs that the server will recognize and respond to.
560
methods: RwLock<Vec<(String, RemoteMethodHandler)>>,
561
}
562
563
impl RemotePlugin {
564
/// Create a [`RemotePlugin`] with the default address and port but without
565
/// any associated methods.
566
fn empty() -> Self {
567
Self {
568
methods: RwLock::new(vec![]),
569
}
570
}
571
572
/// Add a remote method to the plugin using the given `name` and `handler`.
573
#[must_use]
574
pub fn with_method<M>(
575
mut self,
576
name: impl Into<String>,
577
handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,
578
) -> Self {
579
self.methods.get_mut().unwrap().push((
580
name.into(),
581
RemoteMethodHandler::Instant(Box::new(IntoSystem::into_system(handler))),
582
));
583
self
584
}
585
586
/// Add a remote method with a watching handler to the plugin using the given `name`.
587
#[must_use]
588
pub fn with_watching_method<M>(
589
mut self,
590
name: impl Into<String>,
591
handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,
592
) -> Self {
593
self.methods.get_mut().unwrap().push((
594
name.into(),
595
RemoteMethodHandler::Watching(Box::new(IntoSystem::into_system(handler))),
596
));
597
self
598
}
599
}
600
601
impl Default for RemotePlugin {
602
fn default() -> Self {
603
Self::empty()
604
.with_method(
605
builtin_methods::BRP_GET_COMPONENTS_METHOD,
606
builtin_methods::process_remote_get_components_request,
607
)
608
.with_method(
609
builtin_methods::BRP_QUERY_METHOD,
610
builtin_methods::process_remote_query_request,
611
)
612
.with_method(
613
builtin_methods::BRP_SPAWN_ENTITY_METHOD,
614
builtin_methods::process_remote_spawn_entity_request,
615
)
616
.with_method(
617
builtin_methods::BRP_INSERT_COMPONENTS_METHOD,
618
builtin_methods::process_remote_insert_components_request,
619
)
620
.with_method(
621
builtin_methods::BRP_REMOVE_COMPONENTS_METHOD,
622
builtin_methods::process_remote_remove_components_request,
623
)
624
.with_method(
625
builtin_methods::BRP_DESPAWN_COMPONENTS_METHOD,
626
builtin_methods::process_remote_despawn_entity_request,
627
)
628
.with_method(
629
builtin_methods::BRP_REPARENT_ENTITIES_METHOD,
630
builtin_methods::process_remote_reparent_entities_request,
631
)
632
.with_method(
633
builtin_methods::BRP_LIST_COMPONENTS_METHOD,
634
builtin_methods::process_remote_list_components_request,
635
)
636
.with_method(
637
builtin_methods::BRP_MUTATE_COMPONENTS_METHOD,
638
builtin_methods::process_remote_mutate_components_request,
639
)
640
.with_method(
641
builtin_methods::RPC_DISCOVER_METHOD,
642
builtin_methods::process_remote_list_methods_request,
643
)
644
.with_watching_method(
645
builtin_methods::BRP_GET_COMPONENTS_AND_WATCH_METHOD,
646
builtin_methods::process_remote_get_components_watching_request,
647
)
648
.with_watching_method(
649
builtin_methods::BRP_LIST_COMPONENTS_AND_WATCH_METHOD,
650
builtin_methods::process_remote_list_components_watching_request,
651
)
652
.with_method(
653
builtin_methods::BRP_GET_RESOURCE_METHOD,
654
builtin_methods::process_remote_get_resources_request,
655
)
656
.with_method(
657
builtin_methods::BRP_INSERT_RESOURCE_METHOD,
658
builtin_methods::process_remote_insert_resources_request,
659
)
660
.with_method(
661
builtin_methods::BRP_REMOVE_RESOURCE_METHOD,
662
builtin_methods::process_remote_remove_resources_request,
663
)
664
.with_method(
665
builtin_methods::BRP_MUTATE_RESOURCE_METHOD,
666
builtin_methods::process_remote_mutate_resources_request,
667
)
668
.with_method(
669
builtin_methods::BRP_LIST_RESOURCES_METHOD,
670
builtin_methods::process_remote_list_resources_request,
671
)
672
.with_method(
673
builtin_methods::BRP_REGISTRY_SCHEMA_METHOD,
674
builtin_methods::export_registry_types,
675
)
676
}
677
}
678
679
impl Plugin for RemotePlugin {
680
fn build(&self, app: &mut App) {
681
let mut remote_methods = RemoteMethods::new();
682
683
let plugin_methods = &mut *self.methods.write().unwrap();
684
for (name, handler) in plugin_methods.drain(..) {
685
remote_methods.insert(
686
name,
687
match handler {
688
RemoteMethodHandler::Instant(system) => RemoteMethodSystemId::Instant(
689
app.main_mut().world_mut().register_boxed_system(system),
690
),
691
RemoteMethodHandler::Watching(system) => RemoteMethodSystemId::Watching(
692
app.main_mut().world_mut().register_boxed_system(system),
693
),
694
},
695
);
696
}
697
698
app.init_schedule(RemoteLast)
699
.world_mut()
700
.resource_mut::<MainScheduleOrder>()
701
.insert_after(Last, RemoteLast);
702
703
app.insert_resource(remote_methods)
704
.init_resource::<schemas::SchemaTypesMetadata>()
705
.init_resource::<RemoteWatchingRequests>()
706
.add_systems(PreStartup, setup_mailbox_channel)
707
.configure_sets(
708
RemoteLast,
709
(RemoteSystems::ProcessRequests, RemoteSystems::Cleanup).chain(),
710
)
711
.add_systems(
712
RemoteLast,
713
(
714
(process_remote_requests, process_ongoing_watching_requests)
715
.chain()
716
.in_set(RemoteSystems::ProcessRequests),
717
remove_closed_watching_requests.in_set(RemoteSystems::Cleanup),
718
),
719
);
720
}
721
}
722
723
/// Schedule that contains all systems to process Bevy Remote Protocol requests
724
#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]
725
pub struct RemoteLast;
726
727
/// The systems sets of the [`RemoteLast`] schedule.
728
///
729
/// These can be useful for ordering.
730
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
731
pub enum RemoteSystems {
732
/// Processing of remote requests.
733
ProcessRequests,
734
/// Cleanup (remove closed watchers etc)
735
Cleanup,
736
}
737
738
/// Deprecated alias for [`RemoteSystems`].
739
#[deprecated(since = "0.17.0", note = "Renamed to `RemoteSystems`.")]
740
pub type RemoteSet = RemoteSystems;
741
742
/// A type to hold the allowed types of systems to be used as method handlers.
743
#[derive(Debug)]
744
pub enum RemoteMethodHandler {
745
/// A handler that only runs once and returns one response.
746
Instant(Box<dyn System<In = In<Option<Value>>, Out = BrpResult>>),
747
/// A handler that watches for changes and response when a change is detected.
748
Watching(Box<dyn System<In = In<Option<Value>>, Out = BrpResult<Option<Value>>>>),
749
}
750
751
/// The [`SystemId`] of a function that implements a remote instant method (`world.get_components`, `world.query`, etc.)
752
///
753
/// The first parameter is the JSON value of the `params`. Typically, an
754
/// implementation will deserialize these as the first thing they do.
755
///
756
/// The returned JSON value will be returned as the response. Bevy will
757
/// automatically populate the `id` field before sending.
758
pub type RemoteInstantMethodSystemId = SystemId<In<Option<Value>>, BrpResult>;
759
760
/// The [`SystemId`] of a function that implements a remote watching method (`world.get_components+watch`, `world.list_components+watch`, etc.)
761
///
762
/// The first parameter is the JSON value of the `params`. Typically, an
763
/// implementation will deserialize these as the first thing they do.
764
///
765
/// The optional returned JSON value will be sent as a response. If no
766
/// changes were detected this should be [`None`]. Re-running of this
767
/// handler is done in the [`RemotePlugin`].
768
pub type RemoteWatchingMethodSystemId = SystemId<In<Option<Value>>, BrpResult<Option<Value>>>;
769
770
/// The [`SystemId`] of a function that can be used as a remote method.
771
#[derive(Debug, Clone, Copy)]
772
pub enum RemoteMethodSystemId {
773
/// A handler that only runs once and returns one response.
774
Instant(RemoteInstantMethodSystemId),
775
/// A handler that watches for changes and response when a change is detected.
776
Watching(RemoteWatchingMethodSystemId),
777
}
778
779
/// Holds all implementations of methods known to the server.
780
///
781
/// Custom methods can be added to this list using [`RemoteMethods::insert`].
782
#[derive(Debug, Resource, Default)]
783
pub struct RemoteMethods(HashMap<String, RemoteMethodSystemId>);
784
785
impl RemoteMethods {
786
/// Creates a new [`RemoteMethods`] resource with no methods registered in it.
787
pub fn new() -> Self {
788
default()
789
}
790
791
/// Adds a new method, replacing any existing method with that name.
792
///
793
/// If there was an existing method with that name, returns its handler.
794
pub fn insert(
795
&mut self,
796
method_name: impl Into<String>,
797
handler: RemoteMethodSystemId,
798
) -> Option<RemoteMethodSystemId> {
799
self.0.insert(method_name.into(), handler)
800
}
801
802
/// Get a [`RemoteMethodSystemId`] with its method name.
803
pub fn get(&self, method: &str) -> Option<&RemoteMethodSystemId> {
804
self.0.get(method)
805
}
806
807
/// Get a [`Vec<String>`] with method names.
808
pub fn methods(&self) -> Vec<String> {
809
self.0.keys().cloned().collect()
810
}
811
}
812
813
/// Holds the [`BrpMessage`]'s of all ongoing watching requests along with their handlers.
814
#[derive(Debug, Resource, Default)]
815
pub struct RemoteWatchingRequests(Vec<(BrpMessage, RemoteWatchingMethodSystemId)>);
816
817
/// A single request from a Bevy Remote Protocol client to the server,
818
/// serialized in JSON.
819
///
820
/// The JSON payload is expected to look like this:
821
///
822
/// ```json
823
/// {
824
/// "jsonrpc": "2.0",
825
/// "method": "world.get_components",
826
/// "id": 0,
827
/// "params": {
828
/// "entity": 4294967298,
829
/// "components": [
830
/// "bevy_transform::components::transform::Transform"
831
/// ]
832
/// }
833
/// }
834
/// ```
835
/// Or, to list all the fully-qualified type paths in **your** project, pass Null to the
836
/// `params`.
837
/// ```json
838
/// {
839
/// "jsonrpc": "2.0",
840
/// "method": "world.list_components",
841
/// "id": 0,
842
/// "params": null
843
///}
844
///```
845
///
846
/// In Rust:
847
/// ```ignore
848
/// let req = BrpRequest {
849
/// jsonrpc: "2.0".to_string(),
850
/// method: BRP_LIST_METHOD.to_string(), // All the methods have consts
851
/// id: Some(ureq::json!(0)),
852
/// params: None,
853
/// };
854
/// ```
855
#[derive(Debug, Serialize, Deserialize, Clone)]
856
pub struct BrpRequest {
857
/// This field is mandatory and must be set to `"2.0"` for the request to be accepted.
858
pub jsonrpc: String,
859
860
/// The action to be performed.
861
pub method: String,
862
863
/// Arbitrary data that will be returned verbatim to the client as part of
864
/// the response.
865
#[serde(skip_serializing_if = "Option::is_none")]
866
pub id: Option<Value>,
867
868
/// The parameters, specific to each method.
869
///
870
/// These are passed as the first argument to the method handler.
871
/// Sometimes params can be omitted.
872
#[serde(skip_serializing_if = "Option::is_none")]
873
pub params: Option<Value>,
874
}
875
876
/// A response according to BRP.
877
#[derive(Debug, Serialize, Deserialize, Clone)]
878
pub struct BrpResponse {
879
/// This field is mandatory and must be set to `"2.0"`.
880
pub jsonrpc: &'static str,
881
882
/// The id of the original request.
883
pub id: Option<Value>,
884
885
/// The actual response payload.
886
#[serde(flatten)]
887
pub payload: BrpPayload,
888
}
889
890
impl BrpResponse {
891
/// Generates a [`BrpResponse`] from an id and a `Result`.
892
#[must_use]
893
pub fn new(id: Option<Value>, result: BrpResult) -> Self {
894
Self {
895
jsonrpc: "2.0",
896
id,
897
payload: BrpPayload::from(result),
898
}
899
}
900
}
901
902
/// A result/error payload present in every response.
903
#[derive(Debug, Serialize, Deserialize, Clone)]
904
#[serde(rename_all = "snake_case")]
905
pub enum BrpPayload {
906
/// `Ok` variant
907
Result(Value),
908
/// `Err` variant
909
Error(BrpError),
910
}
911
912
impl From<BrpResult> for BrpPayload {
913
fn from(value: BrpResult) -> Self {
914
match value {
915
Ok(v) => Self::Result(v),
916
Err(err) => Self::Error(err),
917
}
918
}
919
}
920
921
/// An error a request might return.
922
#[derive(Debug, Serialize, Deserialize, Clone)]
923
pub struct BrpError {
924
/// Defines the general type of the error.
925
pub code: i16,
926
/// Short, human-readable description of the error.
927
pub message: String,
928
/// Optional additional error data.
929
#[serde(skip_serializing_if = "Option::is_none")]
930
pub data: Option<Value>,
931
}
932
933
impl BrpError {
934
/// Entity wasn't found.
935
#[must_use]
936
pub fn entity_not_found(entity: Entity) -> Self {
937
Self {
938
code: error_codes::ENTITY_NOT_FOUND,
939
message: format!("Entity {entity} not found"),
940
data: None,
941
}
942
}
943
944
/// Component wasn't found in an entity.
945
#[must_use]
946
pub fn component_not_present(component: &str, entity: Entity) -> Self {
947
Self {
948
code: error_codes::COMPONENT_NOT_PRESENT,
949
message: format!("Component `{component}` not present in Entity {entity}"),
950
data: None,
951
}
952
}
953
954
/// An arbitrary component error. Possibly related to reflection.
955
#[must_use]
956
pub fn component_error<E: ToString>(error: E) -> Self {
957
Self {
958
code: error_codes::COMPONENT_ERROR,
959
message: error.to_string(),
960
data: None,
961
}
962
}
963
964
/// Resource was not present in the world.
965
#[must_use]
966
pub fn resource_not_present(resource: &str) -> Self {
967
Self {
968
code: error_codes::RESOURCE_NOT_PRESENT,
969
message: format!("Resource `{resource}` not present in the world"),
970
data: None,
971
}
972
}
973
974
/// An arbitrary resource error. Possibly related to reflection.
975
#[must_use]
976
pub fn resource_error<E: ToString>(error: E) -> Self {
977
Self {
978
code: error_codes::RESOURCE_ERROR,
979
message: error.to_string(),
980
data: None,
981
}
982
}
983
984
/// An arbitrary internal error.
985
#[must_use]
986
pub fn internal<E: ToString>(error: E) -> Self {
987
Self {
988
code: error_codes::INTERNAL_ERROR,
989
message: error.to_string(),
990
data: None,
991
}
992
}
993
994
/// Attempt to reparent an entity to itself.
995
#[must_use]
996
pub fn self_reparent(entity: Entity) -> Self {
997
Self {
998
code: error_codes::SELF_REPARENT,
999
message: format!("Cannot reparent Entity {entity} to itself"),
1000
data: None,
1001
}
1002
}
1003
}
1004
1005
/// Error codes used by BRP.
1006
pub mod error_codes {
1007
// JSON-RPC errors
1008
// Note that the range -32728 to -32000 (inclusive) is reserved by the JSON-RPC specification.
1009
1010
/// Invalid JSON.
1011
pub const PARSE_ERROR: i16 = -32700;
1012
1013
/// JSON sent is not a valid request object.
1014
pub const INVALID_REQUEST: i16 = -32600;
1015
1016
/// The method does not exist / is not available.
1017
pub const METHOD_NOT_FOUND: i16 = -32601;
1018
1019
/// Invalid method parameter(s).
1020
pub const INVALID_PARAMS: i16 = -32602;
1021
1022
/// Internal error.
1023
pub const INTERNAL_ERROR: i16 = -32603;
1024
1025
// Bevy errors (i.e. application errors)
1026
1027
/// Entity not found.
1028
pub const ENTITY_NOT_FOUND: i16 = -23401;
1029
1030
/// Could not reflect or find component.
1031
pub const COMPONENT_ERROR: i16 = -23402;
1032
1033
/// Could not find component in entity.
1034
pub const COMPONENT_NOT_PRESENT: i16 = -23403;
1035
1036
/// Cannot reparent an entity to itself.
1037
pub const SELF_REPARENT: i16 = -23404;
1038
1039
/// Could not reflect or find resource.
1040
pub const RESOURCE_ERROR: i16 = -23501;
1041
1042
/// Could not find resource in the world.
1043
pub const RESOURCE_NOT_PRESENT: i16 = -23502;
1044
}
1045
1046
/// The result of a request.
1047
pub type BrpResult<T = Value> = Result<T, BrpError>;
1048
1049
/// The requests may occur on their own or in batches.
1050
/// Actual parsing is deferred for the sake of proper
1051
/// error reporting.
1052
#[derive(Debug, Clone, Serialize, Deserialize)]
1053
#[serde(untagged)]
1054
pub enum BrpBatch {
1055
/// Multiple requests with deferred parsing.
1056
Batch(Vec<Value>),
1057
/// A single request with deferred parsing.
1058
Single(Value),
1059
}
1060
1061
/// A message from the Bevy Remote Protocol server thread to the main world.
1062
///
1063
/// This is placed in the [`BrpReceiver`].
1064
#[derive(Debug, Clone)]
1065
pub struct BrpMessage {
1066
/// The request method.
1067
pub method: String,
1068
1069
/// The request params.
1070
pub params: Option<Value>,
1071
1072
/// The channel on which the response is to be sent.
1073
///
1074
/// The value sent here is serialized and sent back to the client.
1075
pub sender: Sender<BrpResult>,
1076
}
1077
1078
/// A resource holding the matching sender for the [`BrpReceiver`]'s receiver.
1079
#[derive(Debug, Resource, Deref, DerefMut)]
1080
pub struct BrpSender(Sender<BrpMessage>);
1081
1082
/// A resource that receives messages sent by Bevy Remote Protocol clients.
1083
///
1084
/// Every frame, the `process_remote_requests` system drains this mailbox and
1085
/// processes the messages within.
1086
#[derive(Debug, Resource, Deref, DerefMut)]
1087
pub struct BrpReceiver(Receiver<BrpMessage>);
1088
1089
fn setup_mailbox_channel(mut commands: Commands) {
1090
// Create the channel and the mailbox.
1091
let (request_sender, request_receiver) = async_channel::bounded(CHANNEL_SIZE);
1092
commands.insert_resource(BrpSender(request_sender));
1093
commands.insert_resource(BrpReceiver(request_receiver));
1094
}
1095
1096
/// A system that receives requests placed in the [`BrpReceiver`] and processes
1097
/// them, using the [`RemoteMethods`] resource to map each request to its handler.
1098
///
1099
/// This needs exclusive access to the [`World`] because clients can manipulate
1100
/// anything in the ECS.
1101
fn process_remote_requests(world: &mut World) {
1102
if !world.contains_resource::<BrpReceiver>() {
1103
return;
1104
}
1105
1106
while let Ok(message) = world.resource_mut::<BrpReceiver>().try_recv() {
1107
// Fetch the handler for the method. If there's no such handler
1108
// registered, return an error.
1109
let Some(&handler) = world.resource::<RemoteMethods>().get(&message.method) else {
1110
let _ = message.sender.force_send(Err(BrpError {
1111
code: error_codes::METHOD_NOT_FOUND,
1112
message: format!("Method `{}` not found", message.method),
1113
data: None,
1114
}));
1115
return;
1116
};
1117
1118
match handler {
1119
RemoteMethodSystemId::Instant(id) => {
1120
let result = match world.run_system_with(id, message.params) {
1121
Ok(result) => result,
1122
Err(error) => {
1123
let _ = message.sender.force_send(Err(BrpError {
1124
code: error_codes::INTERNAL_ERROR,
1125
message: format!("Failed to run method handler: {error}"),
1126
data: None,
1127
}));
1128
continue;
1129
}
1130
};
1131
1132
let _ = message.sender.force_send(result);
1133
}
1134
RemoteMethodSystemId::Watching(id) => {
1135
world
1136
.resource_mut::<RemoteWatchingRequests>()
1137
.0
1138
.push((message, id));
1139
}
1140
}
1141
}
1142
}
1143
1144
/// A system that checks all ongoing watching requests for changes that should be sent
1145
/// and handles it if so.
1146
fn process_ongoing_watching_requests(world: &mut World) {
1147
world.resource_scope::<RemoteWatchingRequests, ()>(|world, requests| {
1148
for (message, system_id) in requests.0.iter() {
1149
let handler_result = process_single_ongoing_watching_request(world, message, system_id);
1150
let sender_result = match handler_result {
1151
Ok(Some(value)) => message.sender.try_send(Ok(value)),
1152
Err(err) => message.sender.try_send(Err(err)),
1153
Ok(None) => continue,
1154
};
1155
1156
if sender_result.is_err() {
1157
// The [`remove_closed_watching_requests`] system will clean this up.
1158
message.sender.close();
1159
}
1160
}
1161
});
1162
}
1163
1164
fn process_single_ongoing_watching_request(
1165
world: &mut World,
1166
message: &BrpMessage,
1167
system_id: &RemoteWatchingMethodSystemId,
1168
) -> BrpResult<Option<Value>> {
1169
world
1170
.run_system_with(*system_id, message.params.clone())
1171
.map_err(|error| BrpError {
1172
code: error_codes::INTERNAL_ERROR,
1173
message: format!("Failed to run method handler: {error}"),
1174
data: None,
1175
})?
1176
}
1177
1178
fn remove_closed_watching_requests(mut requests: ResMut<RemoteWatchingRequests>) {
1179
for i in (0..requests.0.len()).rev() {
1180
let Some((message, _)) = requests.0.get(i) else {
1181
unreachable!()
1182
};
1183
1184
if message.sender.is_closed() {
1185
requests.0.swap_remove(i);
1186
}
1187
}
1188
}
1189
1190