Skip to main content

godot_core/obj/
gd.rs

1/*
2 * Copyright (c) godot-rust; Bromeon and contributors.
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6 */
7
8use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
9use std::ops::{Deref, DerefMut};
10
11use godot_ffi as sys;
12use godot_ffi::is_main_thread;
13use sys::{SysPtr as _, static_assert_eq_size_align};
14
15use crate::builtin::{Callable, NodePath, StringName, Variant};
16use crate::meta::error::{ConvertError, FromFfiError};
17use crate::meta::shape::GodotShape;
18use crate::meta::{AsArg, ClassId, Element, FromGodot, GodotConvert, GodotType, RefArg, ToGodot};
19use crate::obj::{
20    Bounds, DynGd, GdDerefTarget, GdMut, GdRef, GodotClass, Inherits, InstanceId, OnEditor, RawGd,
21    WithBaseField, WithSignals, bounds, cap,
22};
23use crate::private::{PanicPayload, callbacks};
24use crate::registry::class::try_dynify_object;
25use crate::registry::info::PropertyHintInfo;
26use crate::registry::property::{Export, SimpleVar, Var};
27use crate::{classes, meta, out};
28
29/// Smart pointer to objects owned by the Godot engine.
30///
31/// See also [chapter about objects][book] in the book.
32///
33/// This smart pointer can only hold _objects_ in the Godot sense: instances of Godot classes (`Node`, `RefCounted`, etc.)
34/// or user-declared structs (declared with `#[derive(GodotClass)]`). It does **not** hold built-in types (`Vector3`, `Color`, `i32`).
35///
36/// `Gd<T>` never holds null objects. If you need nullability, use `Option<Gd<T>>`. To pass null objects to engine APIs, you can
37/// additionally use [`Gd::null_arg()`] as a shorthand.
38///
39/// # Memory management
40///
41/// This smart pointer behaves differently depending on `T`'s associated types, see [`GodotClass`] for their documentation.
42/// In particular, the memory management strategy is fully dependent on `T`:
43///
44/// - **Reference-counted**<br>
45///   Objects of type [`RefCounted`] or inherited from it are **reference-counted**. This means that every time a smart pointer is
46///   shared using [`Clone::clone()`], the reference counter is incremented, and every time one is dropped, it is decremented.
47///   This ensures that the last reference (either in Rust or Godot) will deallocate the object and call `T`'s destructor.<br><br>
48///
49/// - **Manual**<br>
50///   Objects inheriting from [`Object`] which are not `RefCounted` (or inherited) are **manually-managed**.
51///   Their destructor is not automatically called (unless they are part of the scene tree). Creating a `Gd<T>` means that
52///   you are responsible for explicitly deallocating such objects using [`free()`][Self::free].<br><br>
53///
54/// - **Dynamic**<br>
55///   For `T=Object`, the memory strategy is determined **dynamically**. Due to polymorphism, a `Gd<Object>` can point to either
56///   reference-counted or manually-managed types at runtime. The behavior corresponds to one of the two previous points.
57///   Note that if the dynamic type is also `Object`, the memory is manually-managed.
58///
59/// # Construction
60///
61/// To construct default instances of various `Gd<T>` types, there are extension methods on the type `T` itself:
62///
63/// - Manually managed: [`NewAlloc::new_alloc()`][crate::obj::NewAlloc::new_alloc]
64/// - Reference-counted: [`NewGd::new_gd()`][crate::obj::NewGd::new_gd]
65/// - Singletons: `T::singleton()` (inherent)
66///
67/// In addition, the smart pointer can be constructed in multiple ways:
68///
69/// * [`Gd::default()`] for reference-counted types that are constructible. For user types, this means they must expose an `init` function
70///   or have a generated one. `Gd::<T>::default()` is equivalent to the shorter `T::new_gd()` and primarily useful for derives or generics.
71/// * [`Gd::from_init_fn(function)`][Gd::from_init_fn] for Rust objects with `Base<T>` field, which are constructed inside the smart pointer.
72///   This is a very handy function if you want to pass extra parameters to your object upon construction.
73/// * [`Gd::from_object(rust_obj)`][Gd::from_object] for existing Rust objects without a `Base<T>` field that are moved _into_ the smart pointer.
74/// * [`Gd::from_instance_id(id)`][Gd::from_instance_id] and [`Gd::try_from_instance_id(id)`][Gd::try_from_instance_id]
75///   to obtain a pointer to an object which is already alive in the engine.
76///
77/// # Bind guards
78///
79/// The [`bind()`][Self::bind] and [`bind_mut()`][Self::bind_mut] methods allow you to obtain a shared or exclusive guard to the user instance.
80/// These provide interior mutability similar to [`RefCell`][std::cell::RefCell], with the addition that `Gd` simultaneously handles reference
81/// counting (for some types `T`).
82///
83/// Holding a bind guard will prevent other code paths from obtaining their own shared/mutable bind. As such, you should drop the guard
84/// as soon as you don't need it anymore, by closing a `{ }` block or calling `std::mem::drop()`.
85///
86/// When you declare a `#[func]` method on your own class, and it accepts `&self` or `&mut self`, an implicit `bind()` or `bind_mut()` call
87/// 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
88/// 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).
89///
90/// # Conversions
91///
92/// For type conversions, please read the [`godot::meta` module docs][crate::meta].
93///
94/// # Exporting
95///
96/// The [`Export`][crate::registry::property::Export] trait is not directly implemented for `Gd<T>`, because the editor expects object-based
97/// properties to be nullable, while `Gd<T>` can't be null. Instead, `Export` is implemented for [`OnEditor<Gd<T>>`][crate::obj::OnEditor],
98/// which validates that objects have been set by the editor. For the most flexible but least ergonomic option, you can also export
99/// `Option<Gd<T>>` fields.
100///
101/// Objects can only be exported if `T: Inherits<Node>` or `T: Inherits<Resource>`, just like GDScript.
102/// This means you cannot use `#[export]` with `OnEditor<Gd<RefCounted>>`, for example.
103///
104/// [book]: https://godot-rust.github.io/book/godot-api/objects.html
105/// [`Object`]: classes::Object
106/// [`RefCounted`]: classes::RefCounted
107#[repr(C)] // must be layout compatible with engine classes
108pub struct Gd<T: GodotClass> {
109    // Note: `opaque` has the same layout as GDExtensionObjectPtr == Object* in C++, i.e. the bytes represent a pointer
110    // To receive a GDExtensionTypePtr == GDExtensionObjectPtr* == Object**, we need to get the address of this
111    // Hence separate sys() for GDExtensionTypePtr, and obj_sys() for GDExtensionObjectPtr.
112    // The former is the standard FFI type, while the latter is used in object-specific GDExtension engines.
113    // pub(crate) because accessed in obj::dom
114    pub(crate) raw: RawGd<T>,
115}
116
117// Size equality check (should additionally be covered by mem::transmute())
118static_assert_eq_size_align!(
119    sys::GDExtensionObjectPtr,
120    sys::types::OpaqueObject,
121    "Godot FFI: pointer type `Object*` should have size advertised in JSON extension file"
122);
123
124/// _The methods in this impl block are only available for user-declared `T`, that is,
125/// structs with `#[derive(GodotClass)]` but not Godot classes like `Node` or `RefCounted`._ <br><br>
126impl<T> Gd<T>
127where
128    T: GodotClass + Bounds<Declarer = bounds::DeclUser>,
129{
130    /// Creates a `Gd<T>` using a function that constructs a `T` from a provided base.
131    ///
132    /// Imagine you have a type `T`, which has a base field that you cannot default-initialize.
133    /// The `init` function provides you with a `Base<T::Base>` object that you can use inside your `T`, which
134    /// is then wrapped in a `Gd<T>`.
135    ///
136    /// # Example
137    /// ```no_run
138    /// # use godot::prelude::*;
139    /// #[derive(GodotClass)]
140    /// #[class(init, base=Node2D)]
141    /// struct MyClass {
142    ///     my_base: Base<Node2D>,
143    ///     other_field: i32,
144    /// }
145    ///
146    /// let obj = Gd::from_init_fn(|my_base| {
147    ///     // accepts the base and returns a constructed object containing it
148    ///     MyClass { my_base, other_field: 732 }
149    /// });
150    /// ```
151    ///
152    /// # Panics
153    /// Panics occurring in the `init` function are propagated to the caller.
154    pub fn from_init_fn<F>(init: F) -> Self
155    where
156        F: FnOnce(crate::obj::Base<T::Base>) -> T,
157    {
158        let object_ptr = callbacks::create_custom(init, true) // or propagate panic.
159            .unwrap_or_else(|payload| PanicPayload::repanic(payload));
160
161        unsafe { Gd::from_obj_sys(object_ptr) }
162    }
163
164    /// Moves a user-created object into this smart pointer, submitting ownership to the Godot engine.
165    ///
166    /// This is only useful for types `T` which do not store their base objects (if they have a base,
167    /// you cannot construct them standalone).
168    pub fn from_object(user_object: T) -> Self {
169        Self::from_init_fn(move |_base| user_object)
170    }
171
172    /// Hands out a guard for a shared borrow, through which the user instance can be read.
173    ///
174    /// The pattern is very similar to interior mutability with standard [`RefCell`][std::cell::RefCell].
175    /// You can either have multiple `GdRef` shared guards, or a single `GdMut` exclusive guard to a Rust
176    /// `GodotClass` instance, independently of how many `Gd` smart pointers point to it. There are runtime
177    /// checks to ensure that Rust safety rules (e.g. no `&` and `&mut` coexistence) are upheld.
178    ///
179    /// Drop the guard as soon as you don't need it anymore. See also [Bind guards](#bind-guards).
180    ///
181    /// # Panics
182    /// * If another `Gd` smart pointer pointing to the same Rust instance has a live `GdMut` guard bound.
183    /// * If there is an ongoing function call from GDScript to Rust, which currently holds a `&mut T`
184    ///   reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
185    // Note: possible names: write/read, hold/hold_mut, r/w, r/rw, ...
186    pub fn bind(&self) -> GdRef<'_, T> {
187        self.raw.bind()
188    }
189
190    /// Hands out a guard for an exclusive borrow, through which the user instance can be read and written.
191    ///
192    /// The pattern is very similar to interior mutability with standard [`RefCell`][std::cell::RefCell].
193    /// You can either have multiple `GdRef` shared guards, or a single `GdMut` exclusive guard to a Rust
194    /// `GodotClass` instance, independently of how many `Gd` smart pointers point to it. There are runtime
195    /// checks to ensure that Rust safety rules (e.g. no `&mut` aliasing) are upheld.
196    ///
197    /// Drop the guard as soon as you don't need it anymore. See also [Bind guards](#bind-guards).
198    ///
199    /// # Panics
200    /// * If another `Gd` smart pointer pointing to the same Rust instance has a live `GdRef` or `GdMut` guard bound.
201    /// * If there is an ongoing function call from GDScript to Rust, which currently holds a `&T` or `&mut T`
202    ///   reference to the user instance. This can happen through re-entrancy (Rust -> GDScript -> Rust call).
203    pub fn bind_mut(&mut self) -> GdMut<'_, T> {
204        self.raw.bind_mut()
205    }
206}
207
208/// _The methods in this impl block are available for any `T`._ <br><br>
209impl<T: GodotClass> Gd<T> {
210    /// Looks up the given instance ID and returns the associated object, if possible.
211    ///
212    /// If no such instance ID is registered, or if the dynamic type of the object behind that instance ID
213    /// is not compatible with `T`, then `None` is returned.
214    pub fn try_from_instance_id(instance_id: InstanceId) -> Result<Self, ConvertError> {
215        let ptr = classes::object_ptr_from_id(instance_id);
216
217        // SAFETY: assumes that the returned GDExtensionObjectPtr is convertible to Object* (i.e. C++ upcast doesn't modify the pointer)
218        let untyped = unsafe { Gd::<classes::Object>::from_obj_sys_or_none(ptr)? };
219        untyped
220            .owned_cast::<T>()
221            .map_err(|obj| FromFfiError::WrongObjectType.into_error(obj))
222    }
223
224    /// ⚠️ Looks up the given instance ID and returns the associated object.
225    ///
226    /// Corresponds to Godot's global function `instance_from_id()`.
227    ///
228    /// # Panics
229    /// If no such instance ID is registered, or if the dynamic type of the object behind that instance ID
230    /// is not compatible with `T`.
231    #[doc(alias = "instance_from_id")]
232    pub fn from_instance_id(instance_id: InstanceId) -> Self {
233        Self::try_from_instance_id(instance_id).unwrap_or_else(|err| {
234            panic!(
235                "Instance ID {} does not belong to a valid object of class '{}': {}",
236                instance_id,
237                T::class_id(),
238                err
239            )
240        })
241    }
242
243    /// Returns the instance ID of this object, or `None` if the object is dead or null.
244    pub(crate) fn instance_id_or_none(&self) -> Option<InstanceId> {
245        let known_id = self.instance_id_unchecked();
246
247        // Refreshes the internal cached ID on every call, as we cannot be sure that the object has not been
248        // destroyed since last time. The only reliable way to find out is to call is_instance_id_valid().
249        if self.raw.is_instance_valid() {
250            Some(known_id)
251        } else {
252            None
253        }
254    }
255
256    /// ⚠️ Returns the instance ID of this object (panics when dead).
257    ///
258    /// # Panics
259    /// If this object is no longer alive (registered in Godot's object database).
260    pub fn instance_id(&self) -> InstanceId {
261        self.instance_id_or_none().unwrap_or_else(|| {
262            panic!(
263                "failed to call instance_id() on destroyed object; \
264                use instance_id_or_none() or keep your objects alive"
265            )
266        })
267    }
268
269    /// Returns the last known, possibly invalid instance ID of this object.
270    ///
271    /// This function does not check that the returned instance ID points to a valid instance!
272    /// Unless performance is a problem, use [`instance_id()`][Self::instance_id] instead.
273    ///
274    /// This method is safe and never panics.
275    pub fn instance_id_unchecked(&self) -> InstanceId {
276        let instance_id = self.raw.instance_id_unchecked();
277
278        // SAFETY: a `Gd` can only be created from a non-null `RawGd`, meaning `raw.instance_id_unchecked()` will
279        // always return `Some`.
280        unsafe { instance_id.unwrap_unchecked() }
281    }
282
283    /// Checks if this smart pointer points to a live object (read description!).
284    ///
285    /// Using this method is often indicative of bad design -- you should dispose of your pointers once an object is
286    /// destroyed. However, this method exists because GDScript offers it and there may be **rare** use cases.
287    ///
288    /// Do not use this method to check if you can safely access an object. Accessing dead objects is generally safe
289    /// and will panic in a defined manner. Encountering such panics is almost always a bug you should fix, and not a
290    /// runtime condition to check against.
291    pub fn is_instance_valid(&self) -> bool {
292        self.raw.is_instance_valid()
293    }
294
295    /// Returns the dynamic class name of the object as `StringName`.
296    ///
297    /// This method retrieves the class name of the object at runtime, which can be different from [`T::class_id()`][GodotClass::class_id]
298    /// if derived classes are involved.
299    ///
300    /// Unlike [`Object::get_class()`][crate::classes::Object::get_class], this returns `StringName` instead of `GString` and needs no
301    /// `Inherits<Object>` bound.
302    pub(crate) fn dynamic_class_string(&self) -> StringName {
303        unsafe {
304            StringName::new_with_string_uninit(|ptr| {
305                let success = sys::interface_fn!(object_get_class_name)(
306                    self.obj_sys().as_const(),
307                    sys::get_library(),
308                    ptr,
309                );
310
311                let success = sys::conv::bool_from_sys(success);
312                assert!(success, "failed to get class name for object {self:?}");
313            })
314        }
315    }
316
317    /// Returns the reference count, if the dynamic object inherits `RefCounted`; and `None` otherwise.
318    ///
319    /// Returns `Err(())` if obtaining reference count failed, due to being called during init/drop.
320    pub(crate) fn maybe_refcount(&self) -> Option<Result<usize, ()>> {
321        // May become infallible if implemented via call() on Object, if ref-count bit of instance ID is set.
322        // This would likely be more efficient, too.
323
324        // Fast check if ref-counted without downcast.
325        if !self.instance_id().is_ref_counted() {
326            return None;
327        }
328
329        // Optimization: call `get_reference_count()` directly. Might also increase reliability and obviate the need for Result.
330
331        let rc = self
332            .raw
333            .try_with_ref_counted(|refc| refc.get_reference_count());
334
335        Some(rc.map(|i| i as usize))
336    }
337
338    /// Create a non-owning pointer from this.
339    ///
340    /// # Safety
341    /// Must be destroyed with [`drop_weak()`][Self::drop_weak]; regular `Drop` will cause use-after-free.
342    pub(crate) unsafe fn clone_weak(&self) -> Self {
343        // SAFETY: delegated to caller.
344        unsafe { Gd::from_obj_sys_weak(self.obj_sys()) }
345    }
346
347    /// Drop without decrementing ref-counter.
348    ///
349    /// Needed in situations where the instance should effectively be forgotten, but without leaking other associated data.
350    pub(crate) fn drop_weak(self) {
351        // As soon as fields need custom Drop, this won't be enough anymore.
352        std::mem::forget(self);
353    }
354
355    #[cfg(feature = "trace")] // itest only.
356    #[doc(hidden)]
357    pub fn test_refcount(&self) -> Option<usize> {
358        self.maybe_refcount()
359            .transpose()
360            .expect("failed to obtain refcount")
361    }
362
363    /// **Upcast:** convert into a smart pointer to a base class. Always succeeds.
364    ///
365    /// Moves out of this value. If you want to create _another_ smart pointer instance,
366    /// use this idiom:
367    /// ```no_run
368    /// # use godot::prelude::*;
369    /// #[derive(GodotClass)]
370    /// #[class(init, base=Node2D)]
371    /// struct MyClass {}
372    ///
373    /// let obj: Gd<MyClass> = MyClass::new_alloc();
374    /// let base = obj.clone().upcast::<Node>();
375    /// ```
376    pub fn upcast<Base>(self) -> Gd<Base>
377    where
378        Base: GodotClass,
379        T: Inherits<Base>,
380    {
381        self.owned_cast()
382            .expect("Upcast failed. This is a bug; please report it.")
383    }
384
385    /// Equivalent to [`upcast::<Object>()`][Self::upcast], but without bounds.
386    // Not yet public because it might need _mut/_ref overloads, and 6 upcast methods are a bit much...
387    #[doc(hidden)] // no public API, but used by #[signal].
388    pub fn upcast_object(self) -> Gd<classes::Object> {
389        self.owned_cast()
390            .expect("Upcast to Object failed. This is a bug; please report it.")
391    }
392
393    // /// Equivalent to [`upcast_mut::<Object>()`][Self::upcast_mut], but without bounds.
394    // pub(crate) fn upcast_object_ref(&self) -> &classes::Object {
395    //     self.raw.as_object_ref()
396    // }
397
398    /// Equivalent to [`upcast_mut::<Object>()`][Self::upcast_mut], but without bounds.
399    pub(crate) fn upcast_object_mut(&mut self) -> &mut classes::Object {
400        self.raw.as_object_mut()
401    }
402
403    // pub(crate) fn upcast_object_mut_from_ref(&self) -> &mut classes::Object {
404    //     self.raw.as_object_mut()
405    // }
406
407    /// **Upcast shared-ref:** access this object as a shared reference to a base class.
408    ///
409    /// This is semantically equivalent to multiple applications of [`Self::deref()`]. Not really useful on its own, but combined with
410    /// generic programming:
411    /// ```no_run
412    /// # use godot::prelude::*;
413    /// fn print_node_name<T>(node: &Gd<T>)
414    /// where
415    ///     T: Inherits<Node>,
416    /// {
417    ///     println!("Node name: {}", node.upcast_ref().get_name());
418    /// }
419    /// ```
420    ///
421    /// Note that this cannot be used to get a reference to Rust classes, for that you should use [`Gd::bind()`]. For instance this
422    /// will fail:
423    /// ```compile_fail
424    /// # use godot::prelude::*;
425    /// #[derive(GodotClass)]
426    /// #[class(init, base = Node)]
427    /// struct SomeClass {}
428    ///
429    /// #[godot_api]
430    /// impl INode for SomeClass {
431    ///     fn ready(&mut self) {
432    ///         let other = SomeClass::new_alloc();
433    ///         let _ = other.upcast_ref::<SomeClass>();
434    ///     }
435    /// }
436    /// ```
437    pub fn upcast_ref<Base>(&self) -> &Base
438    where
439        Base: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
440        T: Inherits<Base>,
441    {
442        // SAFETY: `Base` is guaranteed to be an engine base class of `T` because of the generic bounds.
443        unsafe { self.raw.as_upcast_ref::<Base>() }
444    }
445
446    /// **Upcast exclusive-ref:** access this object as an exclusive reference to a base class.
447    ///
448    /// This is semantically equivalent to multiple applications of [`Self::deref_mut()`]. Not really useful on its own, but combined with
449    /// generic programming:
450    /// ```no_run
451    /// # use godot::prelude::*;
452    /// fn set_node_name<T>(node: &mut Gd<T>, name: &str)
453    /// where
454    ///     T: Inherits<Node>,
455    /// {
456    ///     node.upcast_mut().set_name(name);
457    /// }
458    /// ```
459    ///
460    /// 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
461    /// will fail:
462    /// ```compile_fail
463    /// # use godot::prelude::*;
464    /// #[derive(GodotClass)]
465    /// #[class(init, base = Node)]
466    /// struct SomeClass {}
467    ///
468    /// #[godot_api]
469    /// impl INode for SomeClass {
470    ///     fn ready(&mut self) {
471    ///         let mut other = SomeClass::new_alloc();
472    ///         let _ = other.upcast_mut::<SomeClass>();
473    ///     }
474    /// }
475    /// ```
476    pub fn upcast_mut<Base>(&mut self) -> &mut Base
477    where
478        Base: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
479        T: Inherits<Base>,
480    {
481        // SAFETY: `Base` is guaranteed to be an engine base class of `T` because of the generic bounds.
482        unsafe { self.raw.as_upcast_mut::<Base>() }
483    }
484
485    /// **Downcast:** try to convert into a smart pointer to a derived class.
486    ///
487    /// If `T`'s dynamic type is not `Derived` or one of its subclasses, `Err(self)` is returned, meaning you can reuse the original
488    /// object for further casts.
489    pub fn try_cast<Derived>(self) -> Result<Gd<Derived>, Self>
490    where
491        Derived: Inherits<T>,
492    {
493        // Separate method due to more restrictive bounds.
494        self.owned_cast()
495    }
496
497    /// ⚠️ **Downcast:** convert into a smart pointer to a derived class. Panics on error.
498    ///
499    /// # Panics
500    /// If the class' dynamic type is not `Derived` or one of its subclasses. Use [`Self::try_cast()`] if you want to check the result.
501    pub fn cast<Derived>(self) -> Gd<Derived>
502    where
503        Derived: Inherits<T>,
504    {
505        self.owned_cast().unwrap_or_else(|from_obj| {
506            panic!(
507                "downcast from {from} to {to} failed; instance {from_obj:?}",
508                from = T::class_id(),
509                to = Derived::class_id(),
510            )
511        })
512    }
513
514    /// Returns `Ok(cast_obj)` on success, `Err(self)` on error.
515    // Visibility: used by DynGd.
516    pub(crate) fn owned_cast<U>(self) -> Result<Gd<U>, Self>
517    where
518        U: GodotClass,
519    {
520        self.raw
521            .owned_cast()
522            .map(Gd::from_ffi)
523            .map_err(Self::from_ffi)
524    }
525
526    /// Create default instance for all types that have `GodotDefault`.
527    ///
528    /// Deliberately more loose than `Gd::default()`, does not require ref-counted memory strategy for user types.
529    pub(crate) fn default_instance() -> Self
530    where
531        T: cap::GodotDefault,
532    {
533        unsafe {
534            // Default value (and compat one) for `p_notify_postinitialize` is true in Godot.
535            #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
536            let object_ptr = callbacks::create::<T>(std::ptr::null_mut(), sys::conv::SYS_TRUE);
537            #[cfg(before_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.4")))]
538            let object_ptr = callbacks::create::<T>(std::ptr::null_mut());
539
540            Gd::from_obj_sys(object_ptr)
541        }
542    }
543
544    /// Upgrades to a `DynGd<T, D>` pointer, enabling the `D` abstraction.
545    ///
546    /// The `D` parameter can typically be inferred when there is a single `AsDyn<...>` implementation for `T`.  \
547    /// Otherwise, use it as `gd.into_dyn::<dyn MyTrait>()`.
548    #[must_use]
549    pub fn into_dyn<D>(self) -> DynGd<T, D>
550    where
551        T: crate::obj::AsDyn<D> + Bounds<Declarer = bounds::DeclUser>,
552        D: ?Sized + 'static,
553    {
554        DynGd::<T, D>::from_gd(self)
555    }
556
557    /// Tries to upgrade to a `DynGd<T, D>` pointer, enabling the `D` abstraction.
558    ///
559    /// If `T`'s dynamic class doesn't implement `AsDyn<D>`, `Err(self)` is returned, meaning you can reuse the original
560    /// object for further casts.
561    pub fn try_dynify<D>(self) -> Result<DynGd<T, D>, Self>
562    where
563        T: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
564        D: ?Sized + 'static,
565    {
566        match try_dynify_object(self) {
567            Ok(dyn_gd) => Ok(dyn_gd),
568            Err((_convert_err, obj)) => Err(obj),
569        }
570    }
571
572    /// Returns a callable referencing a method from this object named `method_name`.
573    ///
574    /// This is shorter syntax for [`Callable::from_object_method(self, method_name)`][Callable::from_object_method].
575    pub fn callable(&self, method_name: impl AsArg<StringName>) -> Callable {
576        Callable::from_object_method(self, method_name)
577    }
578
579    /// Creates a new callable linked to the given object from **single-threaded** Rust function or closure.
580    /// This is shorter syntax for [`Callable::from_linked_fn()`].
581    ///
582    /// `name` is used for the string representation of the closure, which helps with debugging.
583    ///
584    /// Such a callable will be automatically invalidated by Godot when a linked Object is freed.
585    /// If you need a Callable which can live indefinitely, use [`Callable::from_fn()`].
586    pub fn linked_callable<R, F>(
587        &self,
588        method_name: impl Into<crate::builtin::CowStr>,
589        rust_function: F,
590    ) -> Callable
591    where
592        R: ToGodot,
593        F: 'static + FnMut(&[&Variant]) -> R,
594    {
595        Callable::from_linked_fn(method_name, self, rust_function)
596    }
597
598    pub(crate) unsafe fn from_obj_sys_or_none(
599        ptr: sys::GDExtensionObjectPtr,
600    ) -> Result<Self, ConvertError> {
601        unsafe {
602            // Used to have a flag to select RawGd::from_obj_sys_weak(ptr) for Base::to_init_gd(), but solved differently in the end.
603            let obj = RawGd::from_obj_sys(ptr);
604
605            Self::try_from_ffi(obj)
606        }
607    }
608
609    /// Initializes this `Gd<T>` from the object pointer as a **strong ref**, meaning it initializes/increments the reference counter and keeps
610    /// the object alive.
611    ///
612    /// This is the default for most initializations from FFI. In cases where the reference counter should explicitly **not** be updated,
613    /// [`Self::from_obj_sys_weak`] is available.
614    ///
615    /// # Safety
616    /// `ptr` must point to a valid object of this type.
617    pub(crate) unsafe fn from_obj_sys(ptr: sys::GDExtensionObjectPtr) -> Self {
618        sys::strict_assert!(
619            !ptr.is_null(),
620            "Gd::from_obj_sys() called with null pointer"
621        );
622
623        unsafe { Self::from_obj_sys_or_none(ptr) }.unwrap()
624    }
625
626    /// # Safety
627    /// `ptr` must point to a valid object of this type, or null.
628    pub(crate) unsafe fn from_obj_sys_weak_or_none(
629        ptr: sys::GDExtensionObjectPtr,
630    ) -> Result<Self, ConvertError> {
631        unsafe { Self::try_from_ffi(RawGd::from_obj_sys_weak(ptr)) }
632    }
633
634    /// # Safety
635    /// `ptr` must point to a valid object of this type.
636    pub(crate) unsafe fn from_obj_sys_weak(ptr: sys::GDExtensionObjectPtr) -> Self {
637        unsafe { Self::from_obj_sys_weak_or_none(ptr).unwrap() }
638    }
639
640    #[cfg(feature = "trace")] // itest only.
641    #[doc(hidden)]
642    pub unsafe fn __from_obj_sys_weak(ptr: sys::GDExtensionObjectPtr) -> Self {
643        unsafe { Self::from_obj_sys_weak(ptr) }
644    }
645
646    #[doc(hidden)]
647    pub fn obj_sys(&self) -> sys::GDExtensionObjectPtr {
648        self.raw.obj_sys()
649    }
650
651    #[doc(hidden)]
652    pub fn script_sys(&self) -> sys::GDExtensionScriptLanguagePtr
653    where
654        T: Inherits<classes::ScriptLanguage>,
655    {
656        self.raw.script_sys()
657    }
658
659    /// Runs `init_fn` on the address of a pointer (initialized to null). If that pointer is still null after the `init_fn` call,
660    /// then `None` will be returned; otherwise `Gd::from_obj_sys(ptr)`.
661    ///
662    /// This method will **NOT** increment the reference-count of the object, as it assumes the input to come from a Godot API
663    /// return value.
664    ///
665    /// # Safety
666    /// `init_fn` must be a function that correctly handles a _type pointer_ pointing to an _object pointer_.
667    #[doc(hidden)]
668    pub unsafe fn from_sys_init_opt(init_fn: impl FnOnce(sys::GDExtensionTypePtr)) -> Option<Self> {
669        // TODO(uninit) - should we use GDExtensionUninitializedTypePtr instead? Then update all the builtin codegen...
670        let init_fn = |ptr| {
671            init_fn(sys::SysPtr::force_init(ptr));
672        };
673
674        // Note: see _call_native_mb_ret_obj() in godot-cpp, which does things quite different (e.g. querying the instance binding).
675
676        // Initialize pointer with given function. Return Some(ptr) on success, and None otherwise.
677        // SAFETY: init_fn takes a type-ptr pointing to an object-ptr.
678        let object_ptr = unsafe { super::raw_object_init(init_fn) };
679
680        // Do not increment ref-count; assumed to be return value from FFI.
681        sys::ptr_then(object_ptr, |ptr| unsafe { Gd::from_obj_sys_weak(ptr) })
682    }
683
684    /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
685    ///
686    /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred]. The closure receives
687    /// `&mut Self` allowing direct access to Rust fields and methods.
688    ///
689    /// This method is only available for user-defined classes with a `Base<T>` field.
690    /// For engine classes, use [`run_deferred_gd()`][Self::run_deferred_gd] instead.
691    ///
692    /// See also [`WithBaseField::run_deferred()`] if you are within an `impl` block and have access to `self`.
693    ///
694    /// # Panics
695    /// If called outside the main thread.
696    pub fn run_deferred<F>(&mut self, mut_self_method: F)
697    where
698        T: WithBaseField,
699        F: FnOnce(&mut T) + 'static,
700    {
701        self.run_deferred_gd(move |mut gd| {
702            let mut guard = gd.bind_mut();
703            mut_self_method(&mut *guard);
704        });
705    }
706
707    /// Defers the given closure to run during [idle time](https://docs.godotengine.org/en/stable/classes/class_object.html#class-object-method-call-deferred).
708    ///
709    /// This is a type-safe alternative to [`Object::call_deferred()`][crate::classes::Object::call_deferred]. The closure receives
710    /// `Gd<T>`, which can be used to call engine methods or [`bind()`][Gd::bind]/[`bind_mut()`][Gd::bind_mut] to access the Rust object.
711    ///
712    /// See also [`WithBaseField::run_deferred_gd()`] if you are within an `impl` block and have access to `self`.
713    ///
714    /// # Panics
715    /// If called outside the main thread.
716    pub fn run_deferred_gd<F>(&mut self, gd_function: F)
717    where
718        F: FnOnce(Gd<T>) + 'static,
719    {
720        let obj = self.clone();
721        assert!(
722            is_main_thread(),
723            "`run_deferred` must be called on the main thread"
724        );
725
726        let callable = Callable::from_once_fn("run_deferred", move |_| {
727            gd_function(obj);
728        });
729        callable.call_deferred(&[]);
730    }
731}
732
733/// _The methods in this impl block are only available for objects `T` that are manually managed,
734/// i.e. anything that is not `RefCounted` or inherited from it._ <br><br>
735impl<T> Gd<T>
736where
737    T: GodotClass + Bounds<Memory = bounds::MemManual>,
738{
739    /// Destroy the manually-managed Godot object.
740    ///
741    /// Consumes this smart pointer and renders all other `Gd` smart pointers (as well as any GDScript references) to the same object
742    /// immediately invalid. Using those `Gd` instances will lead to panics, but not undefined behavior.
743    ///
744    /// This operation is **safe** and effectively prevents double-free.
745    ///
746    /// Not calling `free()` on manually-managed instances causes memory leaks, unless their ownership is delegated, for
747    /// example to the node tree in case of nodes.
748    ///
749    /// # Panics
750    /// - When the referred-to object has already been destroyed.
751    /// - When this is invoked on an upcast `Gd<Object>` that dynamically points to a reference-counted type (i.e. operation not supported).
752    /// - When the object is bound by an ongoing `bind()` or `bind_mut()` call (through a separate `Gd` pointer).
753    pub fn free(self) {
754        // Note: this method is NOT invoked when the free() call happens dynamically (e.g. through GDScript or reflection).
755        // As such, do not use it for operations and validations to perform upon destruction.
756
757        // free() is likely to be invoked in destructors during panic unwind. In this case, we cannot panic again.
758        // Instead, we print an error and exit free() immediately. The closure is supposed to be used in a unit return statement.
759        let is_panic_unwind = std::thread::panicking();
760        let error_or_panic = |msg: String| {
761            if is_panic_unwind {
762                if crate::private::has_error_print_level(1) {
763                    crate::godot_error!(
764                        "Encountered 2nd panic in free() during panic unwind; will skip destruction:\n{msg}"
765                    );
766                }
767            } else {
768                panic!("{}", msg);
769            }
770        };
771
772        // TODO disallow for singletons, either only at runtime or both at compile time (new memory policy) and runtime
773        use bounds::Declarer;
774
775        // Runtime check in case of T=Object, no-op otherwise
776        let ref_counted =
777            <<T as Bounds>::DynMemory as bounds::DynMemory>::is_ref_counted(&self.raw);
778        if ref_counted == Some(true) {
779            return error_or_panic(format!(
780                "Called free() on Gd<Object> which points to a RefCounted dynamic type; free() only supported for manually managed types\n\
781                Object: {self:?}"
782            ));
783        }
784
785        // If ref_counted returned None, that means the instance was destroyed
786        if ref_counted != Some(false) || (cfg!(safeguards_balanced) && !self.is_instance_valid()) {
787            return error_or_panic("called free() on already destroyed object".to_string());
788        }
789
790        // If the object is still alive, make sure the dynamic type matches. Necessary because subsequent checks may rely on the
791        // static type information to be correct. This is a no-op in Release mode.
792        // Skip check during panic unwind; would need to rewrite whole thing to use Result instead. Having BOTH panic-in-panic and bad type is
793        // a very unlikely corner case.
794        #[cfg(safeguards_strict)] #[cfg_attr(published_docs, doc(cfg(safeguards_strict)))]
795        if !is_panic_unwind {
796            self.raw
797                .check_dynamic_type(&crate::meta::CallContext::gd::<T>("free"));
798        }
799
800        // SAFETY: object must be alive, which was just checked above. No multithreading here.
801        // Also checked in the C free_instance_func callback, however error message can be more precise here, and we don't need to instruct
802        // the engine about object destruction. Both paths are tested.
803        let bound = unsafe { T::Declarer::is_currently_bound(&self.raw) };
804        if bound {
805            return error_or_panic(
806                "called free() while a bind() or bind_mut() call is active".to_string(),
807            );
808        }
809
810        // SAFETY: object alive as checked.
811        // This destroys the Storage instance, no need to run destructor again.
812        unsafe {
813            sys::interface_fn!(object_destroy)(self.raw.obj_sys());
814        }
815
816        // Deallocate associated data in Gd, without destroying the object pointer itself (already done above).
817        self.drop_weak()
818    }
819}
820
821/// _The methods in this impl block are only available for objects `T` that are reference-counted,
822/// i.e. anything that inherits `RefCounted`._ <br><br>
823impl<T> Gd<T>
824where
825    T: GodotClass + Bounds<Memory = bounds::MemRefCounted>,
826{
827    /// Makes sure that `self` does not share references with other `Gd` instances.
828    ///
829    /// Succeeds if the reference count is 1.
830    /// Otherwise, returns the shared object and its reference count.
831    ///
832    /// ## Example
833    ///
834    /// ```no_run
835    /// use godot::prelude::*;
836    ///
837    /// let obj = RefCounted::new_gd();
838    /// match obj.try_to_unique() {
839    ///    Ok(unique_obj) => {
840    ///        // No other Gd<T> shares a reference with `unique_obj`.
841    ///    },
842    ///    Err((shared_obj, ref_count)) => {
843    ///        // `shared_obj` is the original object `obj`.
844    ///        // `ref_count` is the total number of references (including one held by `shared_obj`).
845    ///    }
846    /// }
847    /// ```
848    pub fn try_to_unique(self) -> Result<Self, (Self, usize)> {
849        use crate::obj::bounds::DynMemory as _;
850
851        match <T as Bounds>::DynMemory::get_ref_count(&self.raw) {
852            Some(1) => Ok(self),
853            Some(ref_count) => Err((self, ref_count)),
854            None => unreachable!(),
855        }
856    }
857}
858
859impl<T> Gd<T>
860where
861    T: GodotClass + Bounds<Declarer = bounds::DeclEngine>,
862{
863    /// Represents `null` when passing an object argument to Godot.
864    ///
865    /// This expression is only intended for function argument lists. It can be used whenever a Godot signature accepts
866    /// [`AsArg<Option<Gd<T>>>`][crate::meta::AsArg]. `Gd::null_arg()` as an argument is equivalent to `Option::<Gd<T>>::None`, but less wordy.
867    ///
868    /// To work with objects that can be null, use `Option<Gd<T>>` instead. For APIs that accept `Variant`, you can pass [`Variant::nil()`].
869    ///
870    /// # Nullability
871    /// <div class="warning">
872    /// The GDExtension API does not inform about nullability of its function parameters. It is up to you to verify that the arguments you pass
873    /// are only null when this is allowed. Doing this wrong should be safe, but can lead to the function call failing.
874    /// </div>
875    ///
876    /// # Example
877    /// ```no_run
878    /// # fn some_node() -> Gd<Node> { unimplemented!() }
879    /// use godot::prelude::*;
880    ///
881    /// let mut shape: Gd<Node> = some_node();
882    /// shape.set_owner(Gd::null_arg());
883    pub fn null_arg() -> impl AsArg<Option<Gd<T>>> {
884        meta::NullArg(std::marker::PhantomData)
885    }
886}
887
888impl<T> Gd<T>
889where
890    T: WithSignals,
891{
892    /// Access user-defined signals of this object.
893    ///
894    /// For classes that have at least one `#[signal]` defined, returns a collection of signal names. Each returned signal has a specialized
895    /// API for connecting and emitting signals in a type-safe way. This method is the equivalent of [`WithUserSignals::signals()`], but when
896    /// called externally (not from `self`). Furthermore, this is also available for engine classes, not just user-defined ones.
897    ///
898    /// When you are within the `impl` of a class, use `self.signals()` directly instead.
899    ///
900    /// If you haven't already, read the [book chapter about signals](https://godot-rust.github.io/book/register/signals.html) for a
901    /// walkthrough.
902    ///
903    /// [`WithUserSignals::signals()`]: crate::obj::WithUserSignals::signals()
904    pub fn signals(&self) -> T::SignalCollection<'_, T> {
905        T::__signals_from_external(self)
906    }
907}
908
909// ----------------------------------------------------------------------------------------------------------------------------------------------
910// Trait impls
911
912/// Dereferences to the nearest engine class, enabling direct calls to its `&self` methods.
913///
914/// For engine classes, returns `T` itself. For user classes, returns `T::Base` (the direct engine base class).
915/// The bound ensures that the target is always an engine-provided class.
916impl<T: GodotClass> Deref for Gd<T>
917where
918    GdDerefTarget<T>: Bounds<Declarer = bounds::DeclEngine>,
919{
920    // Target is always an engine class:
921    // * if T is an engine class => T
922    // * if T is a user class => T::Base
923    type Target = GdDerefTarget<T>;
924
925    fn deref(&self) -> &Self::Target {
926        self.raw.as_target()
927    }
928}
929
930/// Mutably dereferences to the nearest engine class, enabling direct calls to its `&mut self` methods.
931///
932/// For engine classes, returns `T` itself. For user classes, returns `T::Base` (the direct engine base class).
933/// The bound ensures that the target is always an engine-provided class.
934impl<T: GodotClass> DerefMut for Gd<T>
935where
936    GdDerefTarget<T>: Bounds<Declarer = bounds::DeclEngine>,
937{
938    fn deref_mut(&mut self) -> &mut Self::Target {
939        self.raw.as_target_mut()
940    }
941}
942
943impl<T: GodotClass> GodotConvert for Gd<T> {
944    type Via = Gd<T>;
945
946    fn godot_shape() -> GodotShape {
947        use crate::meta::shape::ClassHeritage;
948
949        let heritage = if T::inherits::<classes::Resource>() {
950            ClassHeritage::Resource
951        } else if T::inherits::<classes::Node>() {
952            ClassHeritage::Node
953        } else {
954            ClassHeritage::Other
955        };
956
957        let class_id = T::class_id();
958        GodotShape::Class {
959            class_id,
960            heritage,
961            is_nullable: false,
962        }
963    }
964}
965
966impl<T: GodotClass> ToGodot for Gd<T> {
967    type Pass = meta::ByObject;
968
969    fn to_godot(&self) -> &Self {
970        // Note: Gd<T> never null, so no need to check raw.is_null().
971        self.raw.check_rtti("to_godot");
972        self
973    }
974}
975
976impl<T: GodotClass> FromGodot for Gd<T> {
977    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
978        Ok(via)
979    }
980}
981
982// Keep in sync with DynGd.
983impl<T: GodotClass> GodotType for Gd<T> {
984    // Some #[doc(hidden)] are repeated despite already declared in trait; some IDEs suggest in auto-complete otherwise.
985    type Ffi = RawGd<T>;
986
987    type ToFfi<'f>
988        = RefArg<'f, RawGd<T>>
989    where
990        Self: 'f;
991
992    #[doc(hidden)]
993    fn to_ffi(&self) -> Self::ToFfi<'_> {
994        RefArg::new(&self.raw)
995    }
996
997    #[doc(hidden)]
998    fn into_ffi(self) -> Self::Ffi {
999        self.raw
1000    }
1001
1002    fn try_from_ffi(raw: Self::Ffi) -> Result<Self, ConvertError> {
1003        if raw.is_null() {
1004            Err(FromFfiError::NullRawGd.into_error(raw))
1005        } else {
1006            Ok(Self { raw })
1007        }
1008    }
1009
1010    fn qualifies_as_special_none(from_variant: &Variant) -> bool {
1011        // Behavior in Godot 4.2 when unsetting an #[export]'ed property:
1012        // 🔁 reset button: passes null object pointer inside Variant (as expected).
1013        // 🧹 clear button: sends a NodePath with an empty string (!?).
1014
1015        // We recognize the latter case and return a Gd::null() instead of failing to convert the NodePath.
1016        if let Ok(node_path) = from_variant.try_to::<NodePath>()
1017            && node_path.is_empty()
1018        {
1019            return true;
1020        }
1021
1022        false
1023    }
1024
1025    fn as_object_arg(&self) -> meta::ObjectArg<'_> {
1026        meta::ObjectArg::from_gd(self)
1027    }
1028}
1029
1030impl<T: GodotClass> Element for Gd<T> {}
1031
1032impl<T: GodotClass> Element for Option<Gd<T>> {}
1033
1034impl<T> Default for Gd<T>
1035where
1036    T: cap::GodotDefault + Bounds<Memory = bounds::MemRefCounted>,
1037{
1038    /// Creates a default-constructed `T` inside a smart pointer.
1039    ///
1040    /// This is equivalent to the GDScript expression `T.new()`, and to the shorter Rust expression `T::new_gd()`.
1041    ///
1042    /// This trait is only implemented for reference-counted classes. Classes with manually-managed memory (e.g. `Node`) are not covered,
1043    /// because they need explicit memory management, and deriving `Default` has a high chance of the user forgetting to call `free()` on those.
1044    /// `T::new_alloc()` should be used for those instead.
1045    fn default() -> Self {
1046        T::__godot_default()
1047    }
1048}
1049
1050impl<T: GodotClass> Clone for Gd<T> {
1051    fn clone(&self) -> Self {
1052        out!("Gd::clone");
1053        Self {
1054            raw: self.raw.clone(),
1055        }
1056    }
1057}
1058
1059impl<T: GodotClass> SimpleVar for Gd<T> {}
1060
1061/// See [`Gd` Exporting](struct.Gd.html#exporting) section.
1062impl<T> Export for Option<Gd<T>>
1063where
1064    T: GodotClass + Bounds<Exportable = bounds::Yes>,
1065    Option<Gd<T>>: Var,
1066{
1067    #[doc(hidden)]
1068    fn as_node_class() -> Option<ClassId> {
1069        PropertyHintInfo::object_as_node_class::<T>()
1070    }
1071}
1072
1073impl<T: GodotClass> Default for OnEditor<Gd<T>> {
1074    fn default() -> Self {
1075        OnEditor::gd_invalid()
1076    }
1077}
1078
1079impl<T> GodotConvert for OnEditor<Gd<T>>
1080where
1081    T: GodotClass,
1082    Option<<Gd<T> as GodotConvert>::Via>: GodotType,
1083{
1084    type Via = Option<<Gd<T> as GodotConvert>::Via>;
1085
1086    fn godot_shape() -> GodotShape {
1087        Gd::<T>::godot_shape()
1088    }
1089}
1090
1091impl<T> Var for OnEditor<Gd<T>>
1092where
1093    T: GodotClass,
1094{
1095    // Not Option<...> -- accessing from Rust through Var trait should not expose larger API than OnEditor itself.
1096    type PubType = <Gd<T> as GodotConvert>::Via;
1097
1098    fn var_get(field: &Self) -> Self::Via {
1099        Self::get_property_inner(field)
1100    }
1101
1102    fn var_set(field: &mut Self, value: Self::Via) {
1103        Self::set_property_inner(field, value);
1104    }
1105
1106    fn var_pub_get(field: &Self) -> Self::PubType {
1107        Self::var_get(field).expect("generated #[var(pub)] getter: uninitialized OnEditor<Gd<T>>")
1108    }
1109
1110    fn var_pub_set(field: &mut Self, value: Self::PubType) {
1111        Self::var_set(field, Some(value))
1112    }
1113}
1114
1115/// See [`Gd` Exporting](struct.Gd.html#exporting) section.
1116impl<T> Export for OnEditor<Gd<T>>
1117where
1118    Self: Var,
1119    T: GodotClass + Bounds<Exportable = bounds::Yes>,
1120{
1121    #[doc(hidden)]
1122    fn as_node_class() -> Option<ClassId> {
1123        PropertyHintInfo::object_as_node_class::<T>()
1124    }
1125}
1126
1127impl<T: GodotClass> PartialEq for Gd<T> {
1128    /// ⚠️ Returns whether two `Gd` pointers point to the same object.
1129    ///
1130    /// # Panics
1131    /// When `self` or `other` is dead.
1132    fn eq(&self, other: &Self) -> bool {
1133        // Panics when one is dead
1134        self.instance_id() == other.instance_id()
1135    }
1136}
1137
1138impl<T: GodotClass> Eq for Gd<T> {}
1139
1140impl<T: GodotClass> Display for Gd<T> {
1141    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1142        classes::display_string(self, f)
1143    }
1144}
1145
1146impl<T: GodotClass> Debug for Gd<T> {
1147    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1148        classes::debug_string(self, f, "Gd")
1149    }
1150}
1151
1152impl<T: GodotClass> std::hash::Hash for Gd<T> {
1153    /// ⚠️ Hashes this object based on its instance ID.
1154    ///
1155    /// # Panics
1156    /// When `self` is dead.
1157    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1158        self.instance_id().hash(state);
1159    }
1160}
1161
1162// Gd unwinding across panics does not invalidate any invariants;
1163// its mutability is anyway present, in the Godot engine.
1164impl<T: GodotClass> std::panic::UnwindSafe for Gd<T> {}
1165impl<T: GodotClass> std::panic::RefUnwindSafe for Gd<T> {}