bevy_mod_scripting_bindings/
script_component.rs1use super::{InteropError, ScriptComponentRegistration, ScriptEventRegistration, ScriptValue};
4use crate::ScriptNamespaceAppExt;
5use ::{
6 bevy_app::{App, Plugin},
7 bevy_ecs::component::{Component, Mutable, StorageType},
8};
9use bevy_ecs::{entity::Entity, resource::Resource, world::World};
10use bevy_mod_scripting_script::ScriptAttachment;
11use bevy_platform::collections::HashMap;
12use bevy_reflect::{Reflect, std_traits::ReflectDefault};
13use parking_lot::RwLock;
14use std::sync::Arc;
15
16#[derive(Reflect, Clone, Default, Debug)]
18#[reflect(Default)]
19pub struct DynamicComponent {
20 data: ScriptValue,
21}
22
23impl DynamicComponent {
24 pub fn new(data: ScriptValue) -> Self {
26 Self { data }
27 }
28
29 pub fn data(&self) -> &ScriptValue {
31 &self.data
32 }
33}
34
35pub const SCRIPT_NAMESPACE_PREFIX: &str = "script.";
37
38pub fn script_path(namespace: &str, name: &str) -> String {
40 format!("{namespace}.{name}")
41}
42
43pub fn validate_script_namespace_and_name(namespace: &str, name: &str) -> Result<(), InteropError> {
48 let invalid_segment = |segment: &str| {
49 segment.is_empty() || !segment.chars().all(|c| c.is_alphanumeric() || c == '_')
50 };
51 let Some(rest) = namespace.strip_prefix(SCRIPT_NAMESPACE_PREFIX) else {
52 return Err(InteropError::string(format!(
53 "script namespaces must start with `{SCRIPT_NAMESPACE_PREFIX}` (i.e. `{SCRIPT_NAMESPACE_PREFIX}my_game`), got `{namespace}`. \
54 Other namespaces are the names of crates, which scripts cannot add to."
55 )));
56 };
57 if rest.split('.').any(invalid_segment) {
58 return Err(InteropError::string(format!(
59 "invalid script namespace `{namespace}`: after `{SCRIPT_NAMESPACE_PREFIX}` it must be made up of non empty segments \
60 of letters, digits and underscores separated by dots"
61 )));
62 }
63 if name.is_empty() || name.contains('.') {
64 return Err(InteropError::string(format!(
65 "invalid name `{name}` for something registered in `{namespace}`: it cannot be empty or contain dots"
66 )));
67 }
68 Ok(())
69}
70
71#[derive(Clone, Debug)]
75pub struct ScriptExport {
76 pub name: String,
78 pub namespace: String,
80 pub owner: ScriptAttachment,
82 pub label: String,
84}
85
86impl ScriptExport {
87 pub fn path(&self) -> String {
89 script_path(&self.namespace, &self.name)
90 }
91}
92
93#[derive(Component, Clone, Debug)]
95pub struct ScriptObserverOwner(pub ScriptAttachment);
96
97pub fn remove_script_registrations(world: &mut World, attachment: &ScriptAttachment) {
103 if let Some(registry) = world.get_resource::<AppScriptComponentRegistry>() {
104 let mut registry = registry.write();
105 registry.remove_exports_of(attachment);
106 registry.remove_system_sets_of(attachment);
107 }
108 let observers = world
109 .query::<(Entity, &ScriptObserverOwner)>()
110 .iter(world)
111 .filter(|(_, owner)| owner.0 == *attachment)
112 .map(|(entity, _)| entity)
113 .collect::<Vec<_>>();
114 for observer in observers {
115 world.despawn(observer);
116 }
117}
118
119pub struct DynamicComponentInfo {
121 pub name: String,
123 pub namespace: String,
125 pub registration: ScriptComponentRegistration,
127}
128
129impl DynamicComponentInfo {
130 pub fn path(&self) -> String {
132 script_path(&self.namespace, &self.name)
133 }
134}
135
136impl Component for DynamicComponent {
137 const STORAGE_TYPE: StorageType = StorageType::Table;
138 type Mutability = Mutable;
139}
140
141#[derive(Clone, Resource, Default)]
143pub struct AppScriptComponentRegistry(pub Arc<RwLock<ScriptComponentRegistry>>);
144
145#[profiling::all_functions]
146impl AppScriptComponentRegistry {
147 pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, ScriptComponentRegistry> {
149 self.0.read()
150 }
151
152 pub fn write(&self) -> parking_lot::RwLockWriteGuard<'_, ScriptComponentRegistry> {
154 self.0.write()
155 }
156}
157
158#[derive(Default)]
159pub struct ScriptComponentRegistry {
161 components: HashMap<String, DynamicComponentInfo>,
162 events: HashMap<String, ScriptEventRegistration>,
163 exports: HashMap<String, ScriptExport>,
164 system_sets: HashMap<String, ScriptAttachment>,
166 generation: u64,
167}
168
169#[profiling::all_functions]
170impl ScriptComponentRegistry {
171 pub fn register(&mut self, info: DynamicComponentInfo) {
173 self.components.insert(info.path(), info);
174 self.generation += 1;
175 }
176
177 pub fn get(&self, path: &str) -> Option<&DynamicComponentInfo> {
179 self.components.get(path)
180 }
181
182 pub fn find(&self, path: &str) -> Option<&DynamicComponentInfo> {
184 self.components.get(path)
185 }
186
187 pub fn generation(&self) -> u64 {
191 self.generation
192 }
193
194 pub fn iter_components(&self) -> impl Iterator<Item = &DynamicComponentInfo> {
196 self.components.values()
197 }
198
199 pub fn register_event(&mut self, registration: ScriptEventRegistration) {
201 self.events
202 .insert(registration.name.to_string(), registration);
203 }
204
205 pub fn get_event(&self, name: &str) -> Option<&ScriptEventRegistration> {
207 self.events.get(name)
208 }
209
210 pub fn register_export(&mut self, export: ScriptExport) -> Result<(), InteropError> {
215 let path = export.path();
216 if let Some(existing) = self.exports.get(&path)
217 && existing.owner != export.owner
218 {
219 return Err(InteropError::string(format!(
220 "`{path}` is already exported by script {}, exports have to be unique",
221 existing.owner
222 )));
223 }
224 if self.components.contains_key(&path)
225 || self.events.contains_key(&path)
226 || self.system_sets.contains_key(&path)
227 {
228 return Err(InteropError::string(format!(
229 "cannot export `{path}`: a script registered component, event or system set has that path"
230 )));
231 }
232 self.exports.insert(path, export);
233 Ok(())
234 }
235
236 pub fn remove_exports_of(&mut self, owner: &ScriptAttachment) -> usize {
238 let before = self.exports.len();
239 self.exports.retain(|_, export| export.owner != *owner);
240 before - self.exports.len()
241 }
242
243 pub fn get_export(&self, path: &str) -> Option<&ScriptExport> {
245 self.exports.get(path)
246 }
247
248 pub fn iter_exports_in<'a>(
250 &'a self,
251 namespace: &'a str,
252 ) -> impl Iterator<Item = &'a ScriptExport> {
253 self.exports
254 .values()
255 .filter(move |e| e.namespace == namespace)
256 }
257
258 pub fn iter_events_in<'a>(
260 &'a self,
261 namespace: &'a str,
262 ) -> impl Iterator<Item = (&'a str, &'a ScriptEventRegistration)> {
263 self.events.iter().filter_map(move |(path, event)| {
264 let (event_namespace, name) = path.rsplit_once('.')?;
266 (event_namespace == namespace).then_some((name, event))
267 })
268 }
269
270 pub fn export_and_event_namespaces(&self) -> impl Iterator<Item = &str> {
272 self.exports.values().map(|e| e.namespace.as_str()).chain(
273 self.events
274 .keys()
275 .chain(self.system_sets.keys())
276 .filter_map(|p| Some(p.rsplit_once('.')?.0)),
277 )
278 }
279
280 pub fn register_system_set(&mut self, path: String, owner: ScriptAttachment) {
282 self.system_sets.insert(path, owner);
283 }
284
285 pub fn get_system_set_owner(&self, path: &str) -> Option<&ScriptAttachment> {
287 self.system_sets.get(path)
288 }
289
290 pub fn remove_system_sets_of(&mut self, owner: &ScriptAttachment) -> usize {
294 let before = self.system_sets.len();
295 self.system_sets.retain(|_, set_owner| set_owner != owner);
296 before - self.system_sets.len()
297 }
298
299 pub fn iter_system_sets_in<'a>(
301 &'a self,
302 namespace: &'a str,
303 ) -> impl Iterator<Item = (&'a str, &'a str)> {
304 self.system_sets.keys().filter_map(move |path| {
305 let (set_namespace, name) = path.rsplit_once('.')?;
306 (set_namespace == namespace).then_some((path.as_str(), name))
307 })
308 }
309}
310
311pub struct DynamicScriptComponentPlugin;
313
314impl Plugin for DynamicScriptComponentPlugin {
315 fn build(&self, app: &mut App) {
316 app.init_resource::<AppScriptComponentRegistry>()
317 .register_type::<DynamicComponent>()
318 .override_script_namespace::<DynamicComponent>("bms");
319 }
320}
321
322#[cfg(test)]
323mod test {
324 use bevy_ecs::world::World;
325 use bevy_mod_scripting_world::{WorldAccessGuard, WorldGuard};
326
327 use crate::{CurrentScriptAttachment, WorldExtensions};
328
329 use super::*;
330
331 #[test]
332 fn test_script_component() {
333 let mut world = World::new();
334 world.init_resource::<AppScriptComponentRegistry>();
335 let cache = WorldGuard::setup_cache(&world, CurrentScriptAttachment::empty());
336 let registration = {
337 let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
338
339 guard
340 .register_script_component("script.test", "ScriptTest", false)
341 .unwrap()
342 };
343
344 let registry = world.get_resource::<AppScriptComponentRegistry>().unwrap();
345
346 let registry = registry.read();
347 let info = registry.get("script.test.ScriptTest").unwrap();
348 assert_eq!(info.registration.component_id, registration.component_id);
349 assert_eq!(info.name, "ScriptTest");
350 assert_eq!(info.registration.namespace(), "script.test");
351
352 let component = world
354 .components()
355 .get_info(info.registration.component_id)
356 .unwrap();
357
358 assert_eq!(component.name(), "script.test.ScriptTest".into());
359 }
360}