Struct DynGd
pub struct DynGd<T, D>where
T: GodotClass,
D: ?Sized,{ /* private fields */ }
Expand description
Smart pointer integrating Rust traits via dyn
dispatch.
DynGd<T, D>
extends a Godot object Gd<T>
with functionality for Rust’s trait dynamic dispatch.
In this context, the type parameters have the following meaning:
T
is the Godot class.D
is a trait objectdyn Trait
, whereT: Trait
.
To register the T
-> D
relation with godot-rust, T
must implement AsDyn<D>
. This can be automated with the
#[godot_dyn]
attribute macro.
§Construction and API
You can convert between Gd
and DynGd
using Gd::into_dyn()
and DynGd::into_gd()
. The former sometimes needs an explicit
::<dyn Trait>
type argument, but can often be inferred.
The DynGd
API is very close to Gd
. In fact, both Deref
and DerefMut
are implemented for DynGd
-> Gd
, so you can access all the
underlying Gd
methods as well as Godot class APIs directly.
The main new parts are two methods dyn_bind()
and dyn_bind_mut()
. These are very similar to Gd
’s
bind()
and bind_mut()
, but return a reference guard to the trait object D
instead of the Godot class T
.
§Example
use godot::obj::{Gd, DynGd,NewGd};
use godot::register::{godot_dyn, GodotClass};
use godot::classes::RefCounted;
#[derive(GodotClass)]
#[class(init)]
struct Monster {
#[init(val = 100)]
hitpoints: u16,
}
trait Health {
fn is_alive(&self) -> bool;
fn deal_damage(&mut self, damage: u16);
}
// The #[godot_dyn] attribute macro registers the dynamic relation in godot-rust.
// Traits are implemented as usual.
#[godot_dyn]
impl Health for Monster {
fn is_alive(&self) -> bool {
self.hitpoints > 0
}
fn deal_damage(&mut self, damage: u16) {
self.hitpoints = self.hitpoints.saturating_sub(damage);
}
}
// Create a Gd<Monster> and convert it -> DynGd<Monster, dyn Health>.
let monster = Monster::new_gd();
let dyn_monster = monster.into_dyn::<dyn Health>();
// Now upcast it to its base class -> type is DynGd<RefCounted, dyn Health>.
let mut dyn_monster = dyn_monster.upcast::<RefCounted>();
// Due to RefCounted abstraction, you can no longer access concrete Monster properties.
// However, the trait Health is still accessible through dyn_bind().
assert!(dyn_monster.dyn_bind().is_alive());
// To mutate the object, call dyn_bind_mut(). Rust borrow rules apply.
let mut guard = dyn_monster.dyn_bind_mut();
guard.deal_damage(120);
assert!(!guard.is_alive());
§Polymorphic dyn
re-enrichment
When passing DynGd<T, D>
to Godot, you will lose the D
part of the type inside the engine, because Godot doesn’t know about Rust traits.
The trait methods won’t be accessible through GDScript, either.
When receiving objects from Godot, the FromGodot
trait is used to convert values to their Rust counterparts. FromGodot
allows you to
use types in #[func]
parameters or extract elements from arrays, among others. If you now receive a trait-enabled object back from Godot,
you can easily obtain it as Gd<T>
– but what if you need the original DynGd<T, D>
back? If T
is concrete and directly implements D
,
then Gd::into_dyn()
is of course possible. But in reality, you may have a polymorphic base class such as RefCounted
or Node
and
want to ensure that trait object D
dispatches to the correct subclass, without manually checking every possible candidate.
To stay with the above example: let’s say Health
is implemented for two classes Monster
and Knight
. You now have a
DynGd<RefCounted, dyn Health>
, which can represent either of the two classes. We pass this to Godot (e.g. as a Variant
), and then back.
trait Health { /* ... */ }
#[derive(GodotClass)]
struct Monster { /* ... */ }
#[godot_dyn]
impl Health for Monster { /* ... */ }
#[derive(GodotClass)]
struct Knight { /* ... */ }
#[godot_dyn]
impl Health for Knight { /* ... */ }
// Let's construct a DynGd, and pass it to Godot as a Variant.
let variant = if runtime_condition {
// DynGd<Knight, dyn Health>
Knight::new_gd().into_dyn::<dyn Health>().to_variant()
} else {
// DynGd<Monster, dyn Health>
Monster::new_gd().into_dyn::<dyn Health>().to_variant()
};
// Now convert back into a DynGd -- but we don't know the concrete type.
// We can still represent it as DynGd<RefCounted, dyn Health>.
let dyn_gd: DynGd<RefCounted, dyn Health> = variant.to();
// Now work with the abstract object as usual.
When converting from Godot back into DynGd
, we say that the dyn Health
trait object is re-enriched.
godot-rust achieves this thanks to the registration done by #[godot_dyn]
: the library knows for which classes Health
is implemented,
and it can query the dynamic type of the object. Based on that type, it can find the impl Health
implementation matching the correct class.
Behind the scenes, everything is wired up correctly so that you can restore the original DynGd
even after it has passed through Godot.
Implementations§
§impl<T, D> DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> DynGd<T, D>where
T: GodotClass,
D: ?Sized,
pub fn dyn_bind(&self) -> DynGdRef<'_, D>
pub fn dyn_bind(&self) -> DynGdRef<'_, D>
Acquires a shared reference guard to the trait object D
.
The resulting guard implements Deref<Target = D>
, allowing shared access to the trait’s methods.
See Gd::bind()
for borrow checking semantics and panics.
pub fn dyn_bind_mut(&mut self) -> DynGdMut<'_, D>
pub fn dyn_bind_mut(&mut self) -> DynGdMut<'_, D>
Acquires an exclusive reference guard to the trait object D
.
The resulting guard implements DerefMut<Target = D>
, allowing exclusive mutable access to the trait’s methods.
See Gd::bind_mut()
for borrow checking semantics and panics.
pub fn upcast<Base>(self) -> DynGd<Base, D>where
Base: GodotClass,
T: Inherits<Base>,
pub fn upcast<Base>(self) -> DynGd<Base, D>where
Base: GodotClass,
T: Inherits<Base>,
Upcast to a Godot base, while retaining the D
trait object.
This is useful when you want to gather multiple objects under a common Godot base (e.g. Node
), but still enable common functionality.
The common functionality is still accessible through D
even when upcasting.
See also Gd::upcast()
.
pub fn try_cast<Derived>(self) -> Result<DynGd<Derived, D>, DynGd<T, D>>where
Derived: Inherits<T>,
pub fn try_cast<Derived>(self) -> Result<DynGd<Derived, D>, DynGd<T, D>>where
Derived: Inherits<T>,
Downcast to a more specific Godot class, while retaining the D
trait object.
If T
’s dynamic type is not Derived
or one of its subclasses, Err(self)
is returned, meaning you can reuse the original
object for further casts.
See also Gd::try_cast()
.
pub fn cast<Derived>(self) -> DynGd<Derived, D>where
Derived: Inherits<T>,
pub fn cast<Derived>(self) -> DynGd<Derived, D>where
Derived: Inherits<T>,
⚠️ Downcast: to a more specific Godot class, while retaining the D
trait object.
See also Gd::cast()
.
§Panics
If the class’ dynamic type is not Derived
or one of its subclasses. Use Self::try_cast()
if you want to check the result.
§impl<T, D> DynGd<T, D>
impl<T, D> DynGd<T, D>
pub fn free(self)
pub fn free(self)
Destroy the manually-managed Godot object.
See Gd::free()
for semantics and panics.
Methods from Deref<Target = Gd<T>>§
pub fn bind(&self) -> GdRef<'_, T>
pub fn bind(&self) -> GdRef<'_, T>
Hands out a guard for a shared borrow, through which the user instance can be read.
The pattern is very similar to interior mutability with standard RefCell
.
You can either have multiple GdRef
shared guards, or a single GdMut
exclusive guard to a Rust
GodotClass
instance, independently of how many Gd
smart pointers point to it. There are runtime
checks to ensure that Rust safety rules (e.g. no &
and &mut
coexistence) are upheld.
Drop the guard as soon as you don’t need it anymore. See also Bind guards.
§Panics
- If another
Gd
smart pointer pointing to the same Rust instance has a liveGdMut
guard bound. - If there is an ongoing function call from GDScript to Rust, which currently holds a
&mut T
reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
pub fn bind_mut(&mut self) -> GdMut<'_, T>
pub fn bind_mut(&mut self) -> GdMut<'_, T>
Hands out a guard for an exclusive borrow, through which the user instance can be read and written.
The pattern is very similar to interior mutability with standard RefCell
.
You can either have multiple GdRef
shared guards, or a single GdMut
exclusive guard to a Rust
GodotClass
instance, independently of how many Gd
smart pointers point to it. There are runtime
checks to ensure that Rust safety rules (e.g. no &mut
aliasing) are upheld.
Drop the guard as soon as you don’t need it anymore. See also Bind guards.
§Panics
- If another
Gd
smart pointer pointing to the same Rust instance has a liveGdRef
orGdMut
guard bound. - If there is an ongoing function call from GDScript to Rust, which currently holds a
&T
or&mut T
reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
pub fn instance_id(&self) -> InstanceId
pub fn instance_id(&self) -> InstanceId
⚠️ Returns the instance ID of this object (panics when dead).
§Panics
If this object is no longer alive (registered in Godot’s object database).
pub fn instance_id_unchecked(&self) -> InstanceId
pub fn instance_id_unchecked(&self) -> InstanceId
Returns the last known, possibly invalid instance ID of this object.
This function does not check that the returned instance ID points to a valid instance!
Unless performance is a problem, use instance_id()
instead.
This method is safe and never panics.
pub fn is_instance_valid(&self) -> bool
pub fn is_instance_valid(&self) -> bool
Checks if this smart pointer points to a live object (read description!).
Using this method is often indicative of bad design – you should dispose of your pointers once an object is destroyed. However, this method exists because GDScript offers it and there may be rare use cases.
Do not use this method to check if you can safely access an object. Accessing dead objects is generally safe and will panic in a defined manner. Encountering such panics is almost always a bug you should fix, and not a runtime condition to check against.
pub fn upcast_ref<Base>(&self) -> &Base
pub fn upcast_ref<Base>(&self) -> &Base
Upcast shared-ref: access this object as a shared reference to a base class.
This is semantically equivalent to multiple applications of Self::deref()
. Not really useful on its own, but combined with
generic programming:
fn print_node_name<T>(node: &Gd<T>)
where
T: Inherits<Node>,
{
println!("Node name: {}", node.upcast_ref().get_name());
}
Note that this cannot be used to get a reference to Rust classes, for that you should use Gd::bind()
. For instance this
will fail:
#[derive(GodotClass)]
#[class(init, base = Node)]
struct SomeClass {}
#[godot_api]
impl INode for SomeClass {
fn ready(&mut self) {
let other = SomeClass::new_alloc();
let _ = other.upcast_ref::<SomeClass>();
}
}
pub fn upcast_mut<Base>(&mut self) -> &mut Base
pub fn upcast_mut<Base>(&mut self) -> &mut Base
Upcast exclusive-ref: access this object as an exclusive reference to a base class.
This is semantically equivalent to multiple applications of Self::deref_mut()
. Not really useful on its own, but combined with
generic programming:
fn set_node_name<T>(node: &mut Gd<T>, name: &str)
where
T: Inherits<Node>,
{
node.upcast_mut().set_name(name);
}
Note that this cannot be used to get a mutable reference to Rust classes, for that you should use Gd::bind_mut()
. For instance this
will fail:
#[derive(GodotClass)]
#[class(init, base = Node)]
struct SomeClass {}
#[godot_api]
impl INode for SomeClass {
fn ready(&mut self) {
let mut other = SomeClass::new_alloc();
let _ = other.upcast_mut::<SomeClass>();
}
}
pub fn callable(&self, method_name: impl AsArg<StringName>) -> Callable
pub fn callable(&self, method_name: impl AsArg<StringName>) -> Callable
Returns a callable referencing a method from this object named method_name
.
This is shorter syntax for Callable::from_object_method(self, method_name)
.
Trait Implementations§
§impl<T, D> Clone for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> Clone for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> Debug for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> Debug for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> Deref for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> Deref for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> DerefMut for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> DerefMut for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> Display for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> Display for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> FromGodot for DynGd<T, D>where
T: GodotClass,
D: 'static + ?Sized,
impl<T, D> FromGodot for DynGd<T, D>where
T: GodotClass,
D: 'static + ?Sized,
§fn try_from_godot(
via: <DynGd<T, D> as GodotConvert>::Via,
) -> Result<DynGd<T, D>, ConvertError>
fn try_from_godot( via: <DynGd<T, D> as GodotConvert>::Via, ) -> Result<DynGd<T, D>, ConvertError>
Err
on failure.§fn from_godot(via: Self::Via) -> Self
fn from_godot(via: Self::Via) -> Self
§fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>
fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError>
Variant
, returning Err
on failure.§fn from_variant(variant: &Variant) -> Self
fn from_variant(variant: &Variant) -> Self
§impl<T, D> GodotConvert for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> GodotConvert for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> Hash for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
impl<T, D> Hash for DynGd<T, D>where
T: GodotClass,
D: ?Sized,
§impl<T, D> ParamType for DynGd<T, D>where
T: GodotClass,
D: 'static + ?Sized,
impl<T, D> ParamType for DynGd<T, D>where
T: GodotClass,
D: 'static + ?Sized,
§fn owned_to_arg<'v>(self) -> <DynGd<T, D> as ParamType>::Arg<'v>
fn owned_to_arg<'v>(self) -> <DynGd<T, D> as ParamType>::Arg<'v>
impl AsArg<T>
. Read more