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 */
7use crate::builtin::NodePath;
8use crate::classes::{Node, PackedScene};
9use crate::meta::{arg_into_ref, AsArg};
10use crate::obj::{Gd, Inherits};
11
12/// Manual extensions for the `Node` class.
13impl Node {
14    /// ⚠️ Retrieves the node at path `path`, panicking if not found or bad type.
15    ///
16    /// # Panics
17    /// If the node is not found, or if it does not have type `T` or inherited.
18    pub fn get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Gd<T>
19    where
20        T: Inherits<Node>,
21    {
22        arg_into_ref!(path);
23
24        self.try_get_node_as(path).unwrap_or_else(|| {
25            panic!(
26                "There is no node of type {ty} at path `{path}`",
27                ty = T::class_name()
28            )
29        })
30    }
31
32    /// Retrieves the node at path `path` (fallible).
33    ///
34    /// If the node is not found, or if it does not have type `T` or inherited,
35    /// `None` will be returned.
36    pub fn try_get_node_as<T>(&self, path: impl AsArg<NodePath>) -> Option<Gd<T>>
37    where
38        T: Inherits<Node>,
39    {
40        arg_into_ref!(path);
41
42        // TODO differentiate errors (not found, bad type) with Result
43        self.get_node_or_null(path)
44            .and_then(|node| node.try_cast::<T>().ok())
45    }
46}
47
48// ----------------------------------------------------------------------------------------------------------------------------------------------
49
50/// Manual extensions for the `PackedScene` class.
51impl PackedScene {
52    /// ⚠️ Instantiates the scene as type `T`, panicking if not found or bad type.
53    ///
54    /// # Panics
55    /// If the scene is not type `T` or inherited.
56    pub fn instantiate_as<T>(&self) -> Gd<T>
57    where
58        T: Inherits<Node>,
59    {
60        self.try_instantiate_as::<T>()
61            .unwrap_or_else(|| panic!("Failed to instantiate {to}", to = T::class_name()))
62    }
63
64    /// Instantiates the scene as type `T` (fallible).
65    ///
66    /// If the scene is not type `T` or inherited.
67    pub fn try_instantiate_as<T>(&self) -> Option<Gd<T>>
68    where
69        T: Inherits<Node>,
70    {
71        self.instantiate().and_then(|gd| gd.try_cast::<T>().ok())
72    }
73}