66
77use std:: fmt:: { Debug , Display , Formatter , Result as FmtResult } ;
88use std:: ops:: { Deref , DerefMut } ;
9- use std:: ptr;
109
1110use godot_ffi as sys;
1211use godot_ffi:: VariantType ;
@@ -23,28 +22,65 @@ use super::RawGd;
2322
2423/// Smart pointer to objects owned by the Godot engine.
2524///
25+ /// See also [chapter about objects][book] in the book.
26+ ///
2627/// This smart pointer can only hold _objects_ in the Godot sense: instances of Godot classes (`Node`, `RefCounted`, etc.)
27- /// or user-declared structs (`#[derive(GodotClass)]`). It does **not** hold built-in types (`Vector3`, `Color`, `i32`).
28+ /// or user-declared structs (declared with `#[derive(GodotClass)]`). It does **not** hold built-in types (`Vector3`, `Color`, `i32`).
2829///
2930/// `Gd<T>` never holds null objects. If you need nullability, use `Option<Gd<T>>`.
3031///
32+ /// # Memory management
33+ ///
3134/// This smart pointer behaves differently depending on `T`'s associated types, see [`GodotClass`] for their documentation.
3235/// In particular, the memory management strategy is fully dependent on `T`:
3336///
34- /// * Objects of type [`RefCounted`] or inherited from it are **reference-counted**. This means that every time a smart pointer is
37+ /// - **Reference-counted**<br>
38+ /// Objects of type [`RefCounted`] or inherited from it are **reference-counted**. This means that every time a smart pointer is
3539/// shared using [`Clone::clone()`], the reference counter is incremented, and every time one is dropped, it is decremented.
36- /// This ensures that the last reference (either in Rust or Godot) will deallocate the object and call `T`'s destructor.
40+ /// This ensures that the last reference (either in Rust or Godot) will deallocate the object and call `T`'s destructor.<br><br>
3741///
38- /// * Objects inheriting from [`Object`] which are not `RefCounted` (or inherited) are **manually-managed**.
42+ /// - **Manual**<br>
43+ /// Objects inheriting from [`Object`] which are not `RefCounted` (or inherited) are **manually-managed**.
3944/// Their destructor is not automatically called (unless they are part of the scene tree). Creating a `Gd<T>` means that
40- /// you are responsible of explicitly deallocating such objects using [`Gd:: free()`].
45+ /// you are responsible of explicitly deallocating such objects using [`free()`][Self::free].<br><br>
4146///
42- /// * For `T=Object`, the memory strategy is determined **dynamically**. Due to polymorphism, a `Gd<T>` can point to either
47+ /// - **Dynamic**<br>
48+ /// For `T=Object`, the memory strategy is determined **dynamically**. Due to polymorphism, a `Gd<Object>` can point to either
4349/// reference-counted or manually-managed types at runtime. The behavior corresponds to one of the two previous points.
4450/// Note that if the dynamic type is also `Object`, the memory is manually-managed.
4551///
46- /// [`Object`]: crate::engine::Object
47- /// [`RefCounted`]: crate::engine::RefCounted
52+ /// # Construction
53+ ///
54+ /// To construct default instances of various `Gd<T>` types, there are extension methods on the type `T` itself:
55+ ///
56+ /// | Type \ Memory Strategy | Ref-counted | Manually managed | Singleton |
57+ /// |------------------------|----------------------|-----------------------|-------------------------|
58+ /// | **Engine type** | `Resource::new()` | `Node::new_alloc()` | `Os::singleton()` |
59+ /// | **User type** | `MyClass::new_gd()` | `MyClass::alloc_gd()` | _(not yet implemented)_ |
60+ ///
61+ /// In addition, the smart pointer can be constructed in multiple ways:
62+ ///
63+ /// * [`Gd::default()`] for reference-counted types that are constructible. For user types, this means they must expose an `init` function
64+ /// or have a generated one. `Gd::<T>::default()` is equivalent to the shorter `T::new_gd()` and primarily useful for derives or generics.
65+ /// * [`Gd::from_init_fn(function)`][Gd::from_init_fn] for Rust objects with `#[base]` field, which are constructed inside the smart pointer.
66+ /// This is a very handy function if you want to pass extra parameters to your object upon construction.
67+ /// * [`Gd::from_object(rust_obj)`][Gd::from_object] for existing Rust objects without a `#[base]` field that are moved _into_ the smart pointer.
68+ /// * [`Gd::from_instance_id(id)`][Gd::from_instance_id] and [`Gd::try_from_instance_id(id)`][Gd::try_from_instance_id]
69+ /// to obtain a pointer to an object which is already alive in the engine.
70+ ///
71+ /// # Binds
72+ ///
73+ /// The [`bind()`][Self::bind] and [`bind_mut()`][Self::bind_mut] methods allow you to obtain a shared or exclusive guard to the user instance.
74+ /// These provide interior mutability similar to [`RefCell`][std::cell::RefCell], with the addition that `Gd` simultaneously handles reference
75+ /// counting (for some types `T`).
76+ ///
77+ /// When you declare a `#[func]` method on your own class and it accepts `&self` or `&mut self`, an implicit `bind()` or `bind_mut()` call
78+ /// on the owning `Gd<T>` is performed. This is important to keep in mind, as you can get into situations that violate dynamic borrow rules; for
79+ /// example if you are inside a `&mut self` method, make a call to GDScript and indirectly call another method on the same object (re-entrancy).
80+ ///
81+ /// [book]: https://godot-rust.github.io/book/intro/objects.html
82+ /// [`Object`]: engine::Object
83+ /// [`RefCounted`]: engine::RefCounted
4884#[ repr( C ) ] // must be layout compatible with engine classes
4985pub struct Gd < T : GodotClass > {
5086 // Note: `opaque` has the same layout as GDExtensionObjectPtr == Object* in C++, i.e. the bytes represent a pointer
@@ -68,27 +104,6 @@ impl<T> Gd<T>
68104where
69105 T : GodotClass < Declarer = dom:: UserDomain > ,
70106{
71- /// Moves a user-created object into this smart pointer, submitting ownership to the Godot engine.
72- ///
73- /// This is only useful for types `T` which do not store their base objects (if they have a base,
74- /// you cannot construct them standalone).
75- pub fn new ( user_object : T ) -> Self {
76- Self :: with_base ( move |_base| user_object)
77- }
78-
79- /// Creates a default-constructed instance of `T` inside a smart pointer.
80- ///
81- /// This is equivalent to the GDScript expression `T.new()`.
82- pub fn new_default ( ) -> Self
83- where
84- T : cap:: GodotInit ,
85- {
86- unsafe {
87- let object_ptr = callbacks:: create :: < T > ( ptr:: null_mut ( ) ) ;
88- Gd :: from_obj_sys ( object_ptr)
89- }
90- }
91-
92107 /// Creates a `Gd<T>` using a function that constructs a `T` from a provided base.
93108 ///
94109 /// Imagine you have a type `T`, which has a `#[base]` field that you cannot default-initialize.
@@ -106,19 +121,57 @@ where
106121 /// other_field: i32,
107122 /// }
108123 ///
109- /// let obj = Gd::<MyClass>::with_base (|my_base| {
124+ /// let obj = Gd::from_init_fn (|my_base| {
110125 /// // accepts the base and returns a constructed object containing it
111126 /// MyClass { my_base, other_field: 732 }
112127 /// });
113128 /// ```
114- pub fn with_base < F > ( init : F ) -> Self
129+ pub fn from_init_fn < F > ( init : F ) -> Self
115130 where
116131 F : FnOnce ( crate :: obj:: Base < T :: Base > ) -> T ,
117132 {
118133 let object_ptr = callbacks:: create_custom ( init) ;
119134 unsafe { Gd :: from_obj_sys ( object_ptr) }
120135 }
121136
137+ /// Construct default instance for manually managed pointer.
138+ pub fn new_alloc < ManualMem > ( ) -> Self
139+ where
140+ T : GodotClass < Mem = ManualMem > + cap:: GodotDefault ,
141+ ManualMem : mem:: PossiblyManual ,
142+ {
143+ Self :: default_instance ( )
144+ }
145+
146+ /// Moves a user-created object into this smart pointer, submitting ownership to the Godot engine.
147+ ///
148+ /// This is only useful for types `T` which do not store their base objects (if they have a base,
149+ /// you cannot construct them standalone).
150+ pub fn from_object ( user_object : T ) -> Self {
151+ Self :: from_init_fn ( move |_base| user_object)
152+ }
153+
154+ #[ deprecated = "Use `Gd::from_object()` instead." ]
155+ pub fn new ( user_object : T ) -> Self {
156+ Self :: from_object ( user_object)
157+ }
158+
159+ #[ deprecated = "Use `Gd::default()` or the short-hands `T::new_gd()` and `T::alloc_gd()` instead." ]
160+ pub fn new_default ( ) -> Self
161+ where
162+ T : cap:: GodotDefault ,
163+ {
164+ Self :: default_instance ( )
165+ }
166+
167+ #[ deprecated = "Use `Gd::from_init_fn()` instead." ]
168+ pub fn with_base < F > ( init : F ) -> Self
169+ where
170+ F : FnOnce ( crate :: obj:: Base < T :: Base > ) -> T ,
171+ {
172+ Self :: from_init_fn ( init)
173+ }
174+
122175 /// Hands out a guard for a shared borrow, through which the user instance can be read.
123176 ///
124177 /// The pattern is very similar to interior mutability with standard [`RefCell`][std::cell::RefCell].
@@ -242,7 +295,7 @@ impl<T: GodotClass> Gd<T> {
242295 /// #[class(init, base=Node2D)]
243296 /// struct MyClass {}
244297 ///
245- /// let obj: Gd<MyClass> = Gd::new_default ();
298+ /// let obj: Gd<MyClass> = MyClass::alloc_gd ();
246299 /// let base = obj.clone().upcast::<Node>();
247300 /// ```
248301 pub fn upcast < Base > ( self ) -> Gd < Base >
@@ -295,7 +348,19 @@ impl<T: GodotClass> Gd<T> {
295348 . map_err ( Self :: from_ffi)
296349 }
297350
298- #[ doc( hidden) ]
351+ /// Create default instance for all types that have `GodotDefault`.
352+ ///
353+ /// Deliberately more loose than `Gd::default()`, does not require ref-counted memory strategy for user types.
354+ pub ( crate ) fn default_instance ( ) -> Self
355+ where
356+ T : cap:: GodotDefault ,
357+ {
358+ unsafe {
359+ let object_ptr = crate :: callbacks:: create :: < T > ( std:: ptr:: null_mut ( ) ) ;
360+ Gd :: from_obj_sys ( object_ptr)
361+ }
362+ }
363+
299364 pub ( crate ) unsafe fn from_obj_sys_or_none ( ptr : sys:: GDExtensionObjectPtr ) -> Option < Self > {
300365 Self :: try_from_ffi ( RawGd :: from_obj_sys ( ptr) )
301366 }
@@ -305,26 +370,21 @@ impl<T: GodotClass> Gd<T> {
305370 ///
306371 /// This is the default for most initializations from FFI. In cases where reference counter
307372 /// should explicitly **not** be updated, [`Self::from_obj_sys_weak`] is available.
308- #[ doc( hidden) ]
309373 pub ( crate ) unsafe fn from_obj_sys ( ptr : sys:: GDExtensionObjectPtr ) -> Self {
310374 Self :: from_obj_sys_or_none ( ptr) . unwrap ( )
311375 }
312376
313- #[ doc( hidden) ]
314377 pub ( crate ) unsafe fn from_obj_sys_weak_or_none ( ptr : sys:: GDExtensionObjectPtr ) -> Option < Self > {
315378 Self :: try_from_ffi ( RawGd :: from_obj_sys_weak ( ptr) )
316379 }
317380
318- #[ doc( hidden) ]
319381 pub ( crate ) unsafe fn from_obj_sys_weak ( ptr : sys:: GDExtensionObjectPtr ) -> Self {
320382 Self :: from_obj_sys_weak_or_none ( ptr) . unwrap ( )
321383 }
322384
323- #[ doc( hidden) ]
324385 pub ( crate ) fn obj_sys ( & self ) -> sys:: GDExtensionObjectPtr {
325386 self . raw . obj_sys ( )
326387 }
327-
328388 /// Returns a callable referencing a method from this object named `method_name`.
329389 pub fn callable < S : Into < StringName > > ( & self , method_name : S ) -> Callable {
330390 Callable :: from_object_method ( self . clone ( ) , method_name)
@@ -486,6 +546,22 @@ impl<T: GodotClass> GodotType for Gd<T> {
486546 }
487547}
488548
549+ impl < T > Default for Gd < T >
550+ where
551+ T : cap:: GodotDefault + GodotClass < Mem = mem:: StaticRefCount > ,
552+ {
553+ /// Creates a default-constructed `T` inside a smart pointer.
554+ ///
555+ /// This is equivalent to the GDScript expression `T.new()`, and to the shorter Rust expression `T::new_gd()`.
556+ ///
557+ /// This trait is only implemented for reference-counted classes. Classes with manually-managed memory (e.g. `Node`) are not covered,
558+ /// because they need explicit memory management, and deriving `Default` has a high chance of the user forgetting to call `free()` on those.
559+ /// `T::alloc_gd()` should be used for those instead.
560+ fn default ( ) -> Self {
561+ T :: __godot_default ( )
562+ }
563+ }
564+
489565impl < T : GodotClass > Clone for Gd < T > {
490566 fn clone ( & self ) -> Self {
491567 out ! ( "Gd::clone" ) ;
0 commit comments