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