godot_core/classes/
manual_extensions.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
8//! Adds new convenience APIs to existing classes.
9//!
10//! This should not add new functionality, but provide existing one in a slightly nicer way to use. Generally, we should be conservative
11//! about adding methods here, as it's a potentially endless quest, and many are better suited in high-level APIs or third-party crates.
12//!
13//! See also sister module [super::type_safe_replacements].
14
15use crate::builtin::NodePath;
16use crate::classes::{Node, PackedScene};
17use crate::meta::{arg_into_ref, AsArg};
18use crate::obj::{Gd, Inherits};
19
20/// Manual extensions for the `Node` class.
21impl Node {
22    /// ⚠️ Retrieves the node at path `path`, panicking if not found or bad type.
23    ///
24    /// # Panics
25    /// If the node is not found, or if it does not have type `T` or inherited.
26    pub fn get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Gd<T>
27    where
28        T: Inherits<Node>,
29    {
30        arg_into_ref!(path);
31
32        self.try_get_node_as(path).unwrap_or_else(|| {
33            panic!(
34                "There is no node of type {ty} at path `{path}`",
35                ty = T::class_id()
36            )
37        })
38    }
39
40    /// Retrieves the node at path `path` (fallible).
41    ///
42    /// If the node is not found, or if it does not have type `T` or inherited,
43    /// `None` will be returned.
44    pub fn try_get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Option<Gd<T>>
45    where
46        T: Inherits<Node>,
47    {
48        arg_into_ref!(path);
49
50        // TODO differentiate errors (not found, bad type) with Result
51        self.get_node_or_null(path)
52            .and_then(|node| node.try_cast::<T>().ok())
53    }
54}
55
56// ----------------------------------------------------------------------------------------------------------------------------------------------
57
58/// Manual extensions for the `PackedScene` class.
59impl PackedScene {
60    /// ⚠️ Instantiates the scene as type `T`, panicking if not found or bad type.
61    ///
62    /// # Panics
63    /// If the scene is not type `T` or inherited.
64    pub fn instantiate_as<T>(&self) -> Gd<T>
65    where
66        T: Inherits<Node>,
67    {
68        self.try_instantiate_as::<T>()
69            .unwrap_or_else(|| panic!("Failed to instantiate {to}", to = T::class_id()))
70    }
71
72    /// Instantiates the scene as type `T` (fallible).
73    ///
74    /// If the scene is not type `T` or inherited.
75    pub fn try_instantiate_as<T>(&self) -> Option<Gd<T>>
76    where
77        T: Inherits<Node>,
78    {
79        self.instantiate().and_then(|gd| gd.try_cast::<T>().ok())
80    }
81}