Skip to content

Commit c7fba03

Browse files
committed
remove need for world jerry-rig, use static reference
1 parent fe90eaf commit c7fba03

File tree

63 files changed

+259
-1403
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+259
-1403
lines changed

assets/scripts/bevy_api.lua

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,20 @@ end
99

1010
function on_event()
1111
-- send exit event, to finish after one call
12-
world:exit()
12+
world.exit()
1313

1414
print(entity)
1515
print(script)
1616
print(world)
1717

18-
-- print(world:hello(entity, entity))
19-
-- print(world:test_vec({entity, entity})[1])
18+
-- print(world.hello(entity, entity))
19+
-- print(world.test_vec({entity, entity})[1])
2020

2121

22-
local my_component_type = world:get_type_by_name("MyComponent")
22+
local my_component_type = world.get_type_by_name("MyComponent")
2323
print("MyComponent type: ", my_component_type:short_name())
2424

25-
local comp = world:get_component(entity, my_component_type)
25+
local comp = world.get_component(entity, my_component_type)
2626
print("Before script: ", comp:print_value())
2727

2828
print("\noption")
@@ -142,18 +142,18 @@ function on_event()
142142
-- print("F")
143143

144144

145-
-- world:exit()
145+
-- world.exit()
146146
-- do return end
147147
-- print("============")
148148

149149
-- -- this is an example of something impossible to achieve with plain bevy reflection under the hood
150150
-- comp.mat3[1][1] = 42
151151

152152
-- -- now let's retrieve these again to see if we actually changed their values permanently
153-
-- comp = world:get_component(entity,my_component_type)
153+
-- comp = world.get_component(entity,my_component_type)
154154

155155
-- print("After script:")
156156
-- print(comp)
157157

158-
-- world:exit()
158+
-- world.exit()
159159
end

assets/scripts/coroutines.lua

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ function on_update()
1717
coroutine.resume(my_routine)
1818
else
1919
print("Couroutine has finished, no longer running")
20-
world:exit()
20+
world.exit()
2121
end
2222
end
2323
end

assets/scripts/dynamic_queries.lua

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
1-
local component_a = world:get_type_by_name("ComponentA")
2-
local component_b = world:get_type_by_name("ComponentB")
3-
local component_c = world:get_type_by_name("ComponentC")
1+
local component_a = world.get_type_by_name("ComponentA")
2+
local component_b = world.get_type_by_name("ComponentB")
3+
local component_c = world.get_type_by_name("ComponentC")
44

55
print("Querying for entities with component_a and without component_c")
6-
for entity, c in world:query(component_a):without(component_c):iter() do
6+
for entity, c in world.query(component_a):without(component_c):iter() do
77
print("Entity with index: " .. entity:index() .. " component: " .. tostring(c))
88
end
99

1010
print("Querying for entities with component_b and without component_a")
11-
for entity, c in world:query(component_b):without(component_a):iter() do
11+
for entity, c in world.query(component_b):without(component_a):iter() do
1212
print("Entity with index: " .. entity:index() .. " component: " .. tostring(c))
1313
end
1414

1515
print("Querying for all components at once")
16-
for entity, c1,c2,c3 in world:query(component_a, component_b, component_c):iter() do
16+
for entity, c1,c2,c3 in world.query(component_a, component_b, component_c):iter() do
1717
print("Entity with index: " .. entity:index())
1818
print("\tComponentA: " .. tostring(c1))
1919
print("\tComponentB: " .. tostring(c2))
2020
print("\tComponentC: " .. tostring(c3))
2121
end
2222

23-
world:exit()
23+
world.exit()

assets/scripts/game_of_life.lua

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
math.randomseed(os.time())
22

33
function init()
4-
local LifeState = world:get_type_by_name("LifeState")
5-
local life_state = world:get_component(entity,LifeState)
4+
local LifeState = world.get_type_by_name("LifeState")
5+
local life_state = world.get_component(entity,LifeState)
66
local cells = life_state.cells
77

88
-- set some cells alive
@@ -13,15 +13,15 @@ function init()
1313
end
1414

1515
function on_update()
16-
local LifeState = world:get_type_by_name("LifeState")
17-
local Settings = world:get_type_by_name("Settings")
16+
local LifeState = world.get_type_by_name("LifeState")
17+
local Settings = world.get_type_by_name("Settings")
1818

19-
local life_state = world:get_component(entity,LifeState)
19+
local life_state = world.get_component(entity,LifeState)
2020
-- note currently this is a copy of the cells, as of now the macro does not automatically support Vec<T> proxies by reference
2121
local cells = life_state.cells
2222

2323
-- note that here we do not make use of LuaProxyable and just go off pure reflection
24-
local settings = world:get_resource(Settings)
24+
local settings = world.get_resource(Settings)
2525
local dimensions = settings.physical_grid_dimensions
2626

2727

crates/bevy_mod_scripting_core/src/bindings/access_map.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,6 @@ impl ReflectAccessId {
148148
ReflectBase::Resource(id) => Some(Self::for_component_id(id)),
149149
ReflectBase::Component(_, id) => Some(Self::for_component_id(id)),
150150
ReflectBase::Owned(id) => Some(Self::for_allocation(id)),
151-
ReflectBase::World => None,
152151
}
153152
}
154153
}

crates/bevy_mod_scripting_core/src/bindings/function/mod.rs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use bevy::reflect::{
1313
},
1414
PartialReflect,
1515
};
16+
use script_function::CallerContext;
1617

1718
use crate::{
1819
error::{FlattenError, InteropError, InteropErrorInner, ScriptError, ScriptResult},
@@ -32,6 +33,7 @@ pub trait CallScriptFunction {
3233
&self,
3334
args: I,
3435
world: WorldGuard,
36+
context: CallerContext,
3537
) -> Result<ScriptValue, InteropError>;
3638
}
3739

@@ -40,26 +42,22 @@ impl CallScriptFunction for DynamicFunction<'_> {
4042
&self,
4143
args: I,
4244
world: WorldGuard,
45+
context: CallerContext,
4346
) -> Result<ScriptValue, InteropError> {
44-
let mut args = args.into_iter().peekable();
45-
46-
let add_world =
47-
self.first_arg_is_world() && args.peek().map_or(true, |a| a != &ScriptValue::World);
47+
let args = args.into_iter();
4848

49+
let add_context = self.has_caller_context_arg();
4950
let mut args_list = ArgList::new();
5051

51-
if add_world {
52+
if add_context {
53+
args_list = args_list.push_arg(ArgValue::Owned(Box::new(context)));
5254
args_list = args_list.push_arg(ArgValue::Owned(Box::new(
5355
WorldCallbackAccess::from_guard(world.clone()),
5456
)));
5557
}
5658

5759
for arg in args {
58-
let arg_val = ArgValue::Owned(match arg {
59-
ScriptValue::World => Box::new(WorldCallbackAccess::from_guard(world.clone())),
60-
_ => Box::new(arg),
61-
});
62-
60+
let arg_val = ArgValue::Owned(Box::new(arg));
6361
args_list = args_list.push_arg(arg_val);
6462
}
6563

@@ -81,13 +79,13 @@ impl CallScriptFunction for DynamicFunction<'_> {
8179
}
8280

8381
pub trait DynamicFunctionExt {
84-
fn first_arg_is_world(&self) -> bool;
82+
fn has_caller_context_arg(&self) -> bool;
8583
}
8684

8785
impl DynamicFunctionExt for DynamicFunction<'_> {
88-
fn first_arg_is_world(&self) -> bool {
86+
fn has_caller_context_arg(&self) -> bool {
8987
self.info().args().first().map_or(false, |arg| {
90-
arg.type_id() == std::any::TypeId::of::<WorldCallbackAccess>()
88+
arg.type_id() == std::any::TypeId::of::<CallerContext>()
9189
})
9290
}
9391
}

crates/bevy_mod_scripting_core/src/bindings/function/script_function.rs

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use crate::{
88
prelude::{ScriptValue, WorldCallbackAccess},
99
};
1010
use bevy::{
11-
prelude::{AppFunctionRegistry, IntoFunction, World},
11+
prelude::{AppFunctionRegistry, IntoFunction, Reflect, World},
1212
reflect::{
1313
func::{DynamicFunction, FunctionInfo},
1414
FromReflect, GetTypeRegistration, PartialReflect, TypeRegistration, TypeRegistry, Typed,
@@ -85,7 +85,7 @@ macro_rules! register_tuple_dependencies {
8585
}
8686

8787
no_type_dependencies!(ReflectReference, InteropError);
88-
self_type_dependency_only!(WorldCallbackAccess);
88+
self_type_dependency_only!(WorldCallbackAccess, CallerContext);
8989

9090
recursive_type_dependencies!(
9191
(Val<T> where T: GetTypeRegistration),
@@ -103,12 +103,24 @@ pub trait GetFunctionTypeDependencies<Marker> {
103103
fn register_type_dependencies(registry: &mut TypeRegistry);
104104
}
105105

106-
/// The Script Function equivalent for dynamic functions
106+
/// The caller context when calling a script function.
107+
/// Functions can choose to react to caller preferences such as converting 1-indexed numbers to 0-indexed numbers
108+
#[derive(Clone, Copy, Debug, Reflect)]
109+
pub struct CallerContext {
110+
pub convert_to_0_indexed: bool,
111+
}
112+
113+
/// The Script Function equivalent for dynamic functions. Currently unused
107114
/// TODO: have a separate function registry to avoid the need for boxing script args every time
108115
pub struct DynamicScriptFunction {
109116
pub info: FunctionInfo,
110-
pub func:
111-
Arc<dyn Fn(WorldCallbackAccess, Vec<ScriptValue>) -> Result<ScriptValue, InteropError>>,
117+
pub func: Arc<
118+
dyn Fn(
119+
CallerContext,
120+
WorldCallbackAccess,
121+
Vec<ScriptValue>,
122+
) -> Result<ScriptValue, InteropError>,
123+
>,
112124
}
113125

114126
macro_rules! impl_script_function {
@@ -117,31 +129,39 @@ macro_rules! impl_script_function {
117129
// fn(T1...Tn) -> O
118130
impl_script_function!(@ $( $param ),* : -> O => O );
119131
// fn(WorldCallbackAccess, T1...Tn) -> O
120-
impl_script_function!(@ $( $param ),* : (callback: WorldCallbackAccess) -> O => O);
132+
impl_script_function!(@ $( $param ),* : ,(callback: WorldCallbackAccess) -> O => O);
133+
// fn(CallerContext, WorldCallbackAccess, T1...Tn) -> O
134+
impl_script_function!(@ $( $param ),* : (context: CallerContext),(callback: WorldCallbackAccess) -> O => O);
135+
121136
// fn(T1...Tn) -> Result<O, InteropError>
122137
impl_script_function!(@ $( $param ),* : -> O => Result<O, InteropError> where s);
123138
// fn(WorldCallbackAccess, T1...Tn) -> Result<O, InteropError>
124-
impl_script_function!(@ $( $param ),* : (callback: WorldCallbackAccess) -> O => Result<O, InteropError> where s);
139+
impl_script_function!(@ $( $param ),* : ,(callback: WorldCallbackAccess) -> O => Result<O, InteropError> where s);
140+
// fn(CallerContext, WorldCallbackAccess, T1...Tn) -> Result<O, InteropError>
141+
impl_script_function!(@ $( $param ),* : (context: CallerContext),(callback: WorldCallbackAccess) -> O => Result<O, InteropError> where s);
142+
125143
};
126144

127-
(@ $( $param:ident ),* : $(($callback:ident: $callbackty:ty))? -> O => $res:ty $(where $out:ident)?) => {
145+
(@ $( $param:ident ),* : $(($context:ident: $contextty:ty))? $(,($callback:ident: $callbackty:ty))? -> O => $res:ty $(where $out:ident)?) => {
128146
#[allow(non_snake_case)]
129147
impl<
130148
'env,
131149
$( $param: FromScript, )*
132150
O,
133151
F
134152
> ScriptFunction<'env,
135-
fn( $( $callbackty, )? $($param ),* ) -> $res
153+
fn( $($contextty,)? $( $callbackty, )? $($param ),* ) -> $res
136154
> for F
137155
where
138156
O: IntoScript,
139-
F: Fn( $( $callbackty, )? $($param ),* ) -> $res + Send + Sync + 'static,
157+
F: Fn( $($contextty,)? $( $callbackty, )? $($param ),* ) -> $res + Send + Sync + 'static,
140158
$( $param::This<'env>: Into<$param>),*
141159
{
160+
#[allow(unused_variables)]
142161
fn into_dynamic_function(self) -> DynamicFunction<'static> {
143-
(move |world: WorldCallbackAccess, $( $param: ScriptValue ),* | {
162+
(move |caller_context: CallerContext, world: WorldCallbackAccess, $( $param: ScriptValue ),* | {
144163
let res: Result<ScriptValue, InteropError> = (|| {
164+
$( let $context = caller_context; )?
145165
$( let $callback = world.clone(); )?
146166
let world = world.try_read()?;
147167
world.begin_access_scope()?;
@@ -153,7 +173,7 @@ macro_rules! impl_script_function {
153173
let $param = <$param>::from_script($param, world.clone())
154174
.map_err(|e| InteropError::function_arg_conversion_error(current_arg.to_string(), e))?;
155175
)*
156-
let out = self( $( $callback, )? $( $param.into(), )* );
176+
let out = self( $( $context,)? $( $callback, )? $( $param.into(), )* );
157177
$(
158178
let $out = out?;
159179
let out = $out;
@@ -188,8 +208,8 @@ macro_rules! impl_script_function_type_dependencies{
188208
};
189209
}
190210

191-
bevy::utils::all_tuples!(impl_script_function, 0, 14, T);
192-
bevy::utils::all_tuples!(impl_script_function_type_dependencies, 0, 14, T);
211+
bevy::utils::all_tuples!(impl_script_function, 0, 13, T);
212+
bevy::utils::all_tuples!(impl_script_function_type_dependencies, 0, 13, T);
193213

194214
/// Utility for quickly checking your type can be used as an argument in a script function
195215
///

crates/bevy_mod_scripting_core/src/bindings/pretty_print.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,6 @@ impl ReflectReferencePrinter {
7777
ReflectBase::Component(e, _) => format!("Component on entity {}", e),
7878
ReflectBase::Resource(_) => "Resource".to_owned(),
7979
ReflectBase::Owned(_) => "Allocation".to_owned(),
80-
ReflectBase::World => "World".to_owned(),
8180
};
8281

8382
out.push_str(&format!("{}({})", base_kind, type_path));
@@ -403,7 +402,6 @@ impl DisplayWithWorld for ScriptValue {
403402
ScriptValue::Integer(i) => i.to_string(),
404403
ScriptValue::Float(f) => f.to_string(),
405404
ScriptValue::String(cow) => cow.to_string(),
406-
ScriptValue::World => "World".to_owned(),
407405
ScriptValue::Error(script_error) => script_error.to_string(),
408406
ScriptValue::List(vec) => {
409407
let mut string = String::new();

0 commit comments

Comments
 (0)