Skip to content

Commit 421fc0d

Browse files
authored
refactor: remove HandlerCtxt, wrap ScriptContext<P> in Arc (#474)
1 parent 416ee4d commit 421fc0d

File tree

13 files changed

+432
-320
lines changed

13 files changed

+432
-320
lines changed

crates/bevy_mod_scripting_core/src/asset.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,7 @@ fn handle_script_events<P: IntoScriptPluginParams>(
250250

251251
let handle = Handle::Weak(*id);
252252
let attachment = ScriptAttachment::StaticScript(handle.clone());
253+
let script_contexts = script_contexts.read();
253254
for (resident, _) in script_contexts
254255
.residents(&attachment)
255256
.filter(|(r, _)| r.script() == handle && r.is_static())

crates/bevy_mod_scripting_core/src/bindings/script_system.rs

Lines changed: 12 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,14 @@ use super::{
77
access_map::ReflectAccessId,
88
function::{from::Val, into::IntoScript, script_function::AppScriptFunctionRegistry},
99
schedule::AppScheduleRegistry,
10-
script_value::ScriptValue,
1110
};
11+
use crate::extractors::CallContext;
1212
use crate::{
1313
IntoScriptPluginParams,
1414
bindings::pretty_print::DisplayWithWorld,
15-
error::{InteropError, ScriptError},
15+
error::InteropError,
1616
event::CallbackLabel,
1717
extractors::get_all_access_ids,
18-
handler::ScriptingHandler,
1918
script::{ScriptAttachment, ScriptContext},
2019
};
2120
use ::{
@@ -39,10 +38,8 @@ use bevy_ecs::{
3938
};
4039
use bevy_log::{error, info, warn_once};
4140
use bevy_system_reflection::{ReflectSchedule, ReflectSystem};
42-
use parking_lot::Mutex;
4341
use std::{
4442
any::TypeId, borrow::Cow, collections::HashSet, hash::Hash, marker::PhantomData, ops::Deref,
45-
sync::Arc,
4643
};
4744
#[derive(Clone, Hash, PartialEq, Eq)]
4845
/// a system set for script systems.
@@ -198,64 +195,8 @@ impl ScriptSystemBuilder {
198195
}
199196
}
200197

201-
struct DynamicHandlerContext<'w, P: IntoScriptPluginParams> {
202-
script_context: &'w ScriptContext<P>,
203-
}
204-
205-
#[profiling::all_functions]
206-
impl<'w, P: IntoScriptPluginParams> DynamicHandlerContext<'w, P> {
207-
#[allow(
208-
clippy::expect_used,
209-
reason = "cannot avoid panicking inside init_param due to Bevy API structure"
210-
)]
211-
pub fn init_param(world: &mut World, system: &mut FilteredAccessSet<ComponentId>) {
212-
let mut access = FilteredAccess::<ComponentId>::matches_nothing();
213-
214-
let script_context_res_id = world
215-
.resource_id::<ScriptContext<P>>()
216-
.expect("Scripts resource not found");
217-
218-
access.add_resource_read(script_context_res_id);
219-
220-
system.add(access);
221-
}
222-
223-
#[allow(
224-
clippy::expect_used,
225-
reason = "cannot avoid panicking inside get_param due to Bevy API structure"
226-
)]
227-
pub fn get_param(system: &UnsafeWorldCell<'w>) -> Self {
228-
unsafe {
229-
Self {
230-
script_context: system.get_resource().expect("Scripts resource not found"),
231-
}
232-
}
233-
}
234-
235-
/// Call a dynamic label on a script
236-
pub fn call_dynamic_label(
237-
&self,
238-
label: &CallbackLabel,
239-
context_key: &ScriptAttachment,
240-
context: Option<Arc<Mutex<P::C>>>,
241-
payload: Vec<ScriptValue>,
242-
guard: WorldGuard<'_>,
243-
) -> Result<ScriptValue, ScriptError> {
244-
// find script
245-
let Some(context) = context.or_else(|| self.script_context.get(context_key)) else {
246-
return Err(InteropError::missing_context(context_key.clone()).into());
247-
};
248-
249-
// call the script
250-
251-
let mut context = context.lock();
252-
253-
P::handle(payload, context_key, label, &mut context, guard)
254-
}
255-
}
256-
257198
/// TODO: inline world guard into the system state, we should be able to re-use it
258-
struct ScriptSystemState {
199+
struct ScriptSystemState<P: IntoScriptPluginParams> {
259200
type_registry: AppTypeRegistry,
260201
function_registry: AppScriptFunctionRegistry,
261202
schedule_registry: AppScheduleRegistry,
@@ -264,6 +205,7 @@ struct ScriptSystemState {
264205
subset: HashSet<ReflectAccessId>,
265206
callback_label: CallbackLabel,
266207
system_params: Vec<ScriptSystemParam>,
208+
script_contexts: ScriptContext<P>,
267209
}
268210

269211
/// Equivalent of [`SystemParam`] but for dynamic systems, these are the kinds of things
@@ -308,7 +250,7 @@ pub struct DynamicScriptSystem<P: IntoScriptPluginParams> {
308250
target_attachment: ScriptAttachment,
309251
archetype_generation: ArchetypeGeneration,
310252
system_param_descriptors: Vec<ScriptSystemParamDescriptor>,
311-
state: Option<ScriptSystemState>,
253+
state: Option<ScriptSystemState<P>>,
312254
_marker: std::marker::PhantomData<fn() -> P>,
313255
}
314256

@@ -453,16 +395,17 @@ impl<P: IntoScriptPluginParams> System for DynamicScriptSystem<P> {
453395
// targetted scripts. Let's start with just calling the one targetted
454396
// script.
455397

456-
let handler_ctxt = DynamicHandlerContext::<P>::get_param(&world);
398+
let script_context = &state.script_contexts.read();
457399

458-
if let Some(context) = handler_ctxt.script_context.get(&self.target_attachment) {
459-
let result = handler_ctxt.call_dynamic_label(
460-
&state.callback_label,
400+
if let Some(context) = script_context.get_context(&self.target_attachment) {
401+
let mut context = context.lock();
402+
let result = context.call_context_dynamic(
461403
&self.target_attachment,
462-
Some(context),
404+
&state.callback_label,
463405
payload,
464406
guard.clone(),
465407
);
408+
drop(context);
466409
// TODO: Emit error events via commands, maybe accumulate in state
467410
// instead and use apply.
468411
match result {
@@ -552,9 +495,6 @@ impl<P: IntoScriptPluginParams> System for DynamicScriptSystem<P> {
552495
}
553496
}
554497

555-
// TODO: access to internal resources, i.e. handler state
556-
DynamicHandlerContext::<P>::init_param(world, &mut self.component_access_set);
557-
558498
self.state = Some(ScriptSystemState {
559499
type_registry: world.get_resource_or_init::<AppTypeRegistry>().clone(),
560500
function_registry: world
@@ -568,6 +508,7 @@ impl<P: IntoScriptPluginParams> System for DynamicScriptSystem<P> {
568508
subset,
569509
callback_label: self.name.to_string().into(),
570510
system_params,
511+
script_contexts: world.get_resource_or_init::<ScriptContext<P>>().clone(),
571512
})
572513
}
573514

0 commit comments

Comments
 (0)