Skip to content

Commit 13d3514

Browse files
committed
feature: Add DisplayProxy. Refactor continues.
1 parent a2c427a commit 13d3514

File tree

7 files changed

+101
-68
lines changed

7 files changed

+101
-68
lines changed

crates/bevy_mod_scripting_core/src/asset.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::{
55
ScriptComponent,
66
commands::{CreateOrUpdateScript, DeleteScript},
77
error::ScriptError,
8-
script::ScriptId,
8+
script::{DisplayProxy, ScriptId},
99
IntoScriptPluginParams, ScriptingSystemSet,
1010
};
1111
use bevy::{
@@ -151,23 +151,23 @@ pub struct ScriptMetadata {
151151
#[profiling::all_functions]
152152
impl ScriptMetadataStore {
153153
/// Inserts a new metadata entry
154-
pub fn insert(&mut self, id: AssetId<ScriptAsset>, meta: ScriptMetadata) {
154+
pub fn insert(&mut self, id: ScriptId, meta: ScriptMetadata) {
155155
// TODO: new generations of assets are not going to have the same ID as the old one
156156
self.map.insert(id, meta);
157157
}
158158

159159
/// Gets a metadata entry
160-
pub fn get(&self, id: AssetId<ScriptAsset>) -> Option<&ScriptMetadata> {
160+
pub fn get(&self, id: ScriptId) -> Option<&ScriptMetadata> {
161161
self.map.get(&id)
162162
}
163163

164164
/// Removes a metadata entry
165-
pub fn remove(&mut self, id: AssetId<ScriptAsset>) -> Option<ScriptMetadata> {
165+
pub fn remove(&mut self, id: ScriptId) -> Option<ScriptMetadata> {
166166
self.map.remove(&id)
167167
}
168168

169169
/// Checks if the store contains a metadata entry
170-
pub fn contains(&self, id: AssetId<ScriptAsset>) -> bool {
170+
pub fn contains(&self, id: ScriptId) -> bool {
171171
self.map.contains_key(&id)
172172
}
173173
}
@@ -291,7 +291,7 @@ pub(crate) fn sync_script_data<P: IntoScriptPluginParams>(
291291
info!("{}: Loading static script: {:?}", P::LANGUAGE, metadata.asset_id,);
292292
if let Some(asset) = script_assets.get(metadata.asset_id) {
293293
commands.queue(CreateOrUpdateScript::<P>::new(
294-
metadata.asset_id.clone(),
294+
Handle::Weak(metadata.asset_id.clone()),
295295
asset.content.clone(),
296296
Some(script_assets.reserve_handle().clone_weak()),
297297
));
@@ -308,20 +308,20 @@ pub(crate) fn sync_script_data<P: IntoScriptPluginParams>(
308308

309309
pub(crate) fn eval_script<P: IntoScriptPluginParams>(
310310
script_comps: Query<&ScriptComponent, Added<ScriptComponent>>,
311-
mut script_queue: Local<VecDeque<ScriptId>>,
311+
mut script_queue: Local<VecDeque<Handle<ScriptAsset>>>,
312312
script_assets: Res<Assets<ScriptAsset>>,
313313
asset_server: Res<AssetServer>,
314314
mut commands: Commands,
315315
) {
316316
for script_comp in &script_comps {
317317
for handle in &script_comp.0 {
318-
script_queue.push_back(handle.id());
318+
script_queue.push_back(handle.clone_weak());
319319
}
320320
}
321321
while ! script_queue.is_empty() {
322-
let script_ready = script_queue.front().map(|script_id| match asset_server.load_state(*script_id) {
322+
let script_ready = script_queue.front().map(|script_id| match asset_server.load_state(&*script_id) {
323323
LoadState::Failed(e) => {
324-
warn!("Failed to load script {}", &script_id);
324+
warn!("Failed to load script {}", script_id.display());
325325
true
326326
}
327327
LoadState::Loaded => true,
@@ -340,12 +340,12 @@ pub(crate) fn eval_script<P: IntoScriptPluginParams>(
340340
// _ => false
341341
// }) {
342342
if let Some(script_id) = script_queue.pop_front() {
343-
if let Some(asset) = script_assets.get(script_id) {
343+
if let Some(asset) = script_assets.get(&script_id) {
344344
if asset.language == P::LANGUAGE {
345345
commands.queue(CreateOrUpdateScript::<P>::new(
346346
script_id,
347347
asset.content.clone(),
348-
Some(Handle::Weak(script_id)),
348+
None,
349349
));
350350
}
351351
} else {

crates/bevy_mod_scripting_core/src/bindings/script_system.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ impl<'w, P: IntoScriptPluginParams> DynamicHandlerContext<'w, P> {
283283
handler,
284284
payload,
285285
entity,
286-
&script_id.id(),
286+
script_id,
287287
label,
288288
&mut context,
289289
pre_handling_initializers,

crates/bevy_mod_scripting_core/src/commands.rs

Lines changed: 31 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::{
1212
},
1313
extractors::{with_handler_system_state, HandlerContext},
1414
handler::{handle_script_errors, send_callback_response},
15-
script::{Script, ScriptId, Scripts, StaticScripts},
15+
script::{Script, ScriptId, Scripts, StaticScripts, DisplayProxy},
1616
IntoScriptPluginParams,
1717
};
1818
use bevy::{asset::Handle, ecs::entity::Entity, log::debug, prelude::Command};
@@ -41,7 +41,7 @@ impl<P: IntoScriptPluginParams> Command for DeleteScript<P> {
4141
fn apply(self, world: &mut bevy::prelude::World) {
4242
// first apply unload callback
4343
RunScriptCallback::<P>::new(
44-
self.id.clone(),
44+
Handle::Weak(self.id.clone()),
4545
Entity::from_raw(0),
4646
OnScriptUnloaded::into_callback_label(),
4747
vec![],
@@ -65,7 +65,7 @@ impl<P: IntoScriptPluginParams> Command for DeleteScript<P> {
6565
///
6666
/// If script comes from an asset, expects it to be loaded, otherwise this command will fail to process the script.
6767
pub struct CreateOrUpdateScript<P: IntoScriptPluginParams> {
68-
id: ScriptId,
68+
id: Handle<ScriptAsset>,
6969
content: Box<[u8]>,
7070
asset: Option<Handle<ScriptAsset>>,
7171
// Hack to make this Send, C does not need to be Send since it is not stored in the command
@@ -75,7 +75,7 @@ pub struct CreateOrUpdateScript<P: IntoScriptPluginParams> {
7575
#[profiling::all_functions]
7676
impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
7777
/// Creates a new CreateOrUpdateScript command with the given ID, content and asset
78-
pub fn new(id: ScriptId, content: Box<[u8]>, asset: Option<Handle<ScriptAsset>>) -> Self {
78+
pub fn new(id: Handle<ScriptAsset>, content: Box<[u8]>, asset: Option<Handle<ScriptAsset>>) -> Self {
7979
Self {
8080
id,
8181
content,
@@ -84,16 +84,16 @@ impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
8484
}
8585
}
8686

87-
fn script_name(&self) -> String {
88-
self.asset.as_ref().and_then(|handle| handle.path().map(|p| p.to_string())).unwrap_or_else(|| self.id.to_string())
89-
}
87+
// fn script_name(&self) -> String {
88+
// self.asset.as_ref().and_then(|handle| handle.path().map(|p| p.to_string())).unwrap_or_else(|| self.id.to_string())
89+
// }
9090

9191
fn reload_context(
9292
&self,
9393
guard: WorldGuard,
9494
handler_ctxt: &HandlerContext<P>,
9595
) -> Result<(), ScriptError> {
96-
let existing_script = match handler_ctxt.scripts.scripts.get(&self.id) {
96+
let existing_script = match handler_ctxt.scripts.scripts.get(&self.id.id()) {
9797
Some(script) => script,
9898
None => {
9999
return Err(
@@ -108,7 +108,7 @@ impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
108108
(ContextBuilder::<P>::reload)(
109109
handler_ctxt.context_loading_settings.loader.reload,
110110
// &self.id,
111-
&Handle::Weak(self.id),
111+
&self.id,
112112
&self.content,
113113
&mut context,
114114
&handler_ctxt.context_loading_settings.context_initializers,
@@ -130,7 +130,7 @@ impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
130130
let context = (ContextBuilder::<P>::load)(
131131
handler_ctxt.context_loading_settings.loader.load,
132132
// &self.id,
133-
&Handle::Weak(self.id),
133+
&self.id,
134134
&self.content,
135135
&handler_ctxt.context_loading_settings.context_initializers,
136136
&handler_ctxt
@@ -142,8 +142,7 @@ impl<P: IntoScriptPluginParams> CreateOrUpdateScript<P> {
142142

143143
let context = Arc::new(Mutex::new(context));
144144

145-
handler_ctxt.scripts.scripts.insert(
146-
self.id.clone(),
145+
handler_ctxt.scripts.insert(
147146
Script {
148147
id: self.id.clone(),
149148
asset: self.asset.clone(),
@@ -160,7 +159,7 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
160159
let success = with_handler_system_state(
161160
world,
162161
|guard, handler_ctxt: &mut HandlerContext<P>| {
163-
let is_new_script = !handler_ctxt.scripts.scripts.contains_key(&self.id);
162+
let is_new_script = !handler_ctxt.scripts.scripts.contains_key(&self.id.id());
164163

165164
let assigned_shared_context =
166165
match handler_ctxt.context_loading_settings.assignment_strategy {
@@ -181,12 +180,12 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
181180
};
182181

183182
debug!(
184-
"{}: CreateOrUpdateScript command applying (script_id: {}, new context?: {}, new script?: {})",
185-
P::LANGUAGE,
186-
self.id,
187-
assigned_shared_context.is_none(),
188-
is_new_script
189-
);
183+
"{}: CreateOrUpdateScript command applying (script {}, new context?: {}, new script?: {})",
184+
P::LANGUAGE,
185+
self.id.display(),
186+
assigned_shared_context.is_none(),
187+
is_new_script
188+
);
190189

191190
let result = match &assigned_shared_context {
192191
Some(assigned_shared_context) => {
@@ -200,13 +199,13 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
200199
};
201200
// it can potentially be loaded but without a successful script reload but that
202201
// leaves us in an okay state
203-
handler_ctxt.scripts.scripts.insert(self.id.clone(), script);
202+
handler_ctxt.scripts.insert(script);
204203
}
205-
bevy::log::debug!("{}: reloading script with id: {}", P::LANGUAGE, self.id);
204+
bevy::log::debug!("{}: reloading script {}", P::LANGUAGE, self.id.display());
206205
self.reload_context(guard.clone(), handler_ctxt)
207206
}
208207
None => {
209-
bevy::log::debug!("{}: loading script with id: {}", P::LANGUAGE, self.id);
208+
bevy::log::debug!("{}: loading script {}", P::LANGUAGE, self.id.display());
210209
self.load_context(guard.clone(), handler_ctxt)
211210
}
212211
};
@@ -221,7 +220,7 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
221220
handle_script_errors(
222221
guard,
223222
vec![err
224-
.with_script(self.script_name())
223+
.with_script(self.id.display())
225224
.with_context(P::LANGUAGE)
226225
.with_context(phrase)]
227226
.into_iter(),
@@ -230,9 +229,9 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
230229
}
231230

232231
bevy::log::debug!(
233-
"{}: script with id: {} successfully created or updated",
232+
"{}: script {} successfully created or updated",
234233
P::LANGUAGE,
235-
self.id
234+
self.id.display()
236235
);
237236

238237
true
@@ -256,7 +255,7 @@ impl<P: IntoScriptPluginParams> Command for CreateOrUpdateScript<P> {
256255
/// Runs a callback on the script with the given ID if it exists
257256
pub struct RunScriptCallback<P: IntoScriptPluginParams> {
258257
/// The ID of the script to run the callback on
259-
pub id: AssetId<ScriptAsset>,
258+
pub id: Handle<ScriptAsset>,
260259
/// The entity to use for the callback
261260
pub entity: Entity,
262261
/// The callback to run
@@ -274,7 +273,7 @@ pub struct RunScriptCallback<P: IntoScriptPluginParams> {
274273
impl<P: IntoScriptPluginParams> RunScriptCallback<P> {
275274
/// Creates a new RunCallbackCommand with the given ID, callback and arguments
276275
pub fn new(
277-
id: AssetId<ScriptAsset>,
276+
id: Handle<ScriptAsset>,
278277
entity: Entity,
279278
callback: CallbackLabel,
280279
args: Vec<ScriptValue>,
@@ -301,11 +300,11 @@ impl<P: IntoScriptPluginParams> RunScriptCallback<P> {
301300
impl<P: IntoScriptPluginParams> Command for RunScriptCallback<P> {
302301
fn apply(self, world: &mut bevy::prelude::World) {
303302
with_handler_system_state(world, |guard, handler_ctxt: &mut HandlerContext<P>| {
304-
if !handler_ctxt.is_script_fully_loaded(self.id.clone()) {
303+
if !handler_ctxt.is_script_fully_loaded(self.id.id()) {
305304
bevy::log::error!(
306-
"{}: Cannot apply callback command, as script does not exist: {}. Ignoring.",
305+
"{}: Cannot apply callback command, as script {} does not exist. Ignoring.",
307306
P::LANGUAGE,
308-
self.id
307+
self.id.display()
309308
);
310309
return;
311310
}
@@ -323,14 +322,14 @@ impl<P: IntoScriptPluginParams> Command for RunScriptCallback<P> {
323322
guard.clone(),
324323
ScriptCallbackResponseEvent::new(
325324
self.callback,
326-
self.id.clone(),
325+
self.id.id(),
327326
result.clone(),
328327
),
329328
);
330329
}
331330

332331
if let Err(err) = result {
333-
let mut error_with_context = err.with_script(self.id).with_context(P::LANGUAGE);
332+
let mut error_with_context = err.with_script(self.id.display()).with_context(P::LANGUAGE);
334333
if let Some(ctxt) = self.context {
335334
error_with_context = error_with_context.with_context(ctxt);
336335
}

crates/bevy_mod_scripting_core/src/error.rs

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use crate::{
99
script_value::ScriptValue,
1010
ReflectBaseType, ReflectReference,
1111
},
12-
script::ScriptId,
12+
script::{DisplayProxy, ScriptId},
1313
};
1414
use bevy::{
1515
asset::Handle,
@@ -1255,17 +1255,10 @@ macro_rules! unregistered_component_or_resource_type {
12551255

12561256
macro_rules! missing_script_for_callback {
12571257
($script_id:expr) => {
1258-
if let Some(path) = $script_id.path() {
1259-
format!(
1260-
"Could not find script with path: {}. Is the script loaded?",
1261-
path
1262-
)
1263-
} else {
1264-
format!(
1265-
"Could not find script with id: {}. Is the script loaded?",
1266-
$script_id.id()
1267-
)
1268-
}
1258+
format!(
1259+
"Could not find script {}. Is the script loaded?",
1260+
$script_id.display()
1261+
)
12691262
};
12701263
}
12711264

crates/bevy_mod_scripting_core/src/extractors.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use bevy::{
1919
use fixedbitset::FixedBitSet;
2020

2121
use crate::{
22+
ScriptAsset,
2223
bindings::{
2324
access_map::ReflectAccessId, pretty_print::DisplayWithWorld, script_value::ScriptValue,
2425
WorldAccessGuard, WorldGuard,
@@ -208,16 +209,16 @@ impl<P: IntoScriptPluginParams> HandlerContext<'_, P> {
208209
pub fn call_dynamic_label(
209210
&self,
210211
label: &CallbackLabel,
211-
script_id: &ScriptId,
212+
script_id: &Handle<ScriptAsset>,
212213
entity: Entity,
213214
payload: Vec<ScriptValue>,
214215
guard: WorldGuard<'_>,
215216
) -> Result<ScriptValue, ScriptError> {
216217
// find script
217-
let script = match self.scripts.scripts.get(script_id) {
218+
let script = match self.scripts.scripts.get(&script_id.id()) {
218219
Some(script) => script,
219220
// NOTE: It'd be nice to use a handle here because then we have the path.
220-
None => return Err(InteropError::missing_script(Handle::Weak(script_id.clone())).into()),
221+
None => return Err(InteropError::missing_script(script_id.clone()).into()),
221222
};
222223

223224
// call the script
@@ -248,7 +249,7 @@ impl<P: IntoScriptPluginParams> HandlerContext<'_, P> {
248249
/// Run [`Self::is_script_fully_loaded`] before calling the script to ensure the script and context were loaded ahead of time.
249250
pub fn call<C: IntoCallbackLabel>(
250251
&self,
251-
script_id: &ScriptId,
252+
script_id: &Handle<ScriptAsset>,
252253
entity: Entity,
253254
payload: Vec<ScriptValue>,
254255
guard: WorldGuard<'_>,

crates/bevy_mod_scripting_core/src/handler.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ use bevy::{
3131
pub type HandlerFn<P> = fn(
3232
args: Vec<ScriptValue>,
3333
entity: Entity,
34-
script_id: &ScriptId,
34+
script_id: &Handle<ScriptAsset>,
3535
callback: &CallbackLabel,
3636
context: &mut <P as IntoScriptPluginParams>::C,
3737
pre_handling_initializers: &[ContextPreHandlingInitializer<P>],
@@ -73,7 +73,7 @@ impl<P: IntoScriptPluginParams> CallbackSettings<P> {
7373
handler: HandlerFn<P>,
7474
args: Vec<ScriptValue>,
7575
entity: Entity,
76-
script_id: &ScriptId,
76+
script_id: &Handle<ScriptAsset>,
7777
callback: &CallbackLabel,
7878
script_ctxt: &mut P::C,
7979
pre_handling_initializers: &[ContextPreHandlingInitializer<P>],
@@ -199,7 +199,7 @@ pub(crate) fn event_handler_inner<P: IntoScriptPluginParams>(
199199

200200
let call_result = handler_ctxt.call_dynamic_label(
201201
&callback_label,
202-
&script_id.id(),
202+
&script_id,
203203
*entity,
204204
event.args.clone(),
205205
guard.clone(),

0 commit comments

Comments
 (0)