godot/lib.rs
1#![cfg_attr(published_docs, feature(doc_cfg))]
2/*
3 * Copyright (c) godot-rust; Bromeon and contributors.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 */
8
9//! # Rust bindings for Godot 4
10//!
11//! The **gdext** library implements Rust bindings for the [Godot](https://godotengine.org) engine, more precisely its version 4.
12//! It does so using the GDExtension API, a C interface to integrate third-party language bindings with the engine.
13//!
14//! This API doc is accompanied by the [book](https://github.com/godot-rust/book), which provides tutorials
15//! that guide you along the way.
16//!
17//! An overview of fundamental types and concepts can be found on [this page](__docs).
18//!
19//!
20//! ## Module organization
21//!
22//! The contains generated code, which is derived from the GDExtension API specification. This code spans the official Godot API and
23//! is mostly the same as the API you would use in GDScript.
24//!
25//! The Godot API is divided into several modules:
26//!
27//! * [`builtin`]: Built-in types, such as `Vector2`, `Color`, and `String`.
28//! * [`classes`]: Godot classes, such as `Node`, `RefCounted` or `Resource`.
29//! * [`global`]: Global functions and enums, such as `godot_print!`, `smoothstep` or `JoyAxis`.
30//!
31//! In addition to generated code, we provide a framework that allows you to easily interface the Godot engine.
32//! Noteworthy modules in this context are:
33//!
34//! * [`register`], used to register **your own** Rust symbols (classes, methods, constants etc.) with Godot.
35//! * [`obj`], everything related to handling Godot objects, such as the `Gd<T>` type.
36//! * [`signal`], machinery for type-safe signals.
37//! * [`tools`], higher-level utilities that extend the generated code, e.g. `load<T>()`.
38//! * [`meta`], fundamental information about types and conversions.
39//! * [`init`], entry point and global library configuration.
40//! * [`task`], integration with async code.
41//!
42//! The [`prelude`] contains often-imported symbols; feel free to `use godot::prelude::*` in your code.
43//! <br><br>
44//!
45//!
46//! ## Public API
47//!
48//! Some symbols in the API are not intended for users, however Rust's visibility feature is not strong enough to express that in all cases
49//! (for example, proc-macros and separated crates may need access to internals).
50//!
51//! The following API symbols are considered private:
52//!
53//! * Symbols annotated with `#[doc(hidden)]`.
54//! * Any of the dependency crates (crate `godot` is the only public interface).
55//! * Modules named `private` and all their contents.
56//!
57//! This means there are **no guarantees** regarding API stability, robustness or correctness. Problems arising from using private APIs are
58//! not considered bugs, and anything relying on them may stop working without announcement. Please refrain from using undocumented and
59//! private features; if you are missing certain functionality, bring it up for discussion instead. This allows us to improve the library!
60//! <br><br>
61//!
62//!
63//! ## Safeguard levels
64//!
65//! godot-rust uses three tiers that differ in the amount of runtime checks and validations that are performed. \
66//! They can be configured via [Cargo features](#cargo-features).
67//!
68//! - 🛡️ **Strict** (default for dev builds)
69//!
70//! Lots of additional, sometimes expensive checks. Detects many bugs during development.
71//! - `Gd::bind/bind_mut()` provides extensive diagnostics to locate runtime borrow errors.
72//! - `Array` safe conversion checks (for types like `Array<i8>`).
73//! - RTTI checks on object access (protect against type mismatch edge cases).
74//! - Geometric invariants (e.g. normalized quaternions).
75//! - Access to engine APIs outside valid scope.<br><br>
76//!
77//! - ⚖️ **Balanced** (default for release builds)
78//!
79//! Basic validity and invariant checks, reasonably fast. Within this level, you should not be able to encounter undefined behavior (UB)
80//! in safe Rust code. Invariant violations may however cause panics and logic errors.
81//! - Object liveness checks.
82//! - `Gd::bind/bind_mut()` cause panics on borrow errors.<br><br>
83//!
84//! - ☣️ **Disengaged**
85//!
86//! Most checks disabled, sacrifices safety for raw speed. This renders a large part of the godot-rust API `unsafe` without polluting the
87//! code; you opt in via `unsafe impl ExtensionLibrary`.
88//!
89//! Before using this, measure to ensure you truly need the last bit of performance (balanced should be fast enough for most cases; if not,
90//! consider bringing it up). Also test your code thoroughly using the other levels first. Undefined behavior and crashes arising
91//! from using this level are your full responsibility. When reporting a bug, make sure you can reproduce it under the balanced level.
92//! - Unchecked object access -> instant UB if an object is dead.
93//! - `Gd::bind/bind_mut()` are unchecked -> UB if mutable aliasing occurs.
94//!
95//! <div class="warning">
96//! <p>Safeguards are a recent addition to godot-rust and need calibrating over time. If you are unhappy with how the <i>balanced</i> level
97//! performs in basic operations, consider bringing it up for discussion. We'd like to offer the <i>disengaged</i> level for power users who
98//! really need it, but it shouldn't be the only choice for decent runtime performance, as it comes with heavy trade-offs.</p>
99//!
100//! <p>As of v0.4, the above checks are not fully implemented yet. Neither are they guarantees; categorization may change over time.</p>
101//! </div>
102//!
103//!
104//! ## Cargo features
105//!
106//! The following features can be enabled for this crate. All of them are off by default.
107//!
108//! Avoid `default-features = false` unless you know exactly what you are doing; it will disable some required internal features.
109//!
110//! _Godot version and configuration:_
111//!
112//! * **`api-4-{minor}`**
113//! * **`api-custom`**
114//! * **`api-custom-json`**
115//!
116//! Sets the [**API level**](https://godot-rust.github.io/book/toolchain/godot-version.html) to the specified Godot version,
117//! or a custom-built local binary.
118//! You can use at most one `api-*` feature. If absent, the current Godot minor version is used, with patch level 0.
119//!
120//! `api-custom` feature requires specifying `GDRUST_GODOT_BIN` environment variable with a path to your Godot4 binary.
121//!
122//! The `api-custom-json` feature requires specifying `GDRUST_GODOT_API_JSON` environment variable with a path
123//! to your custom-defined `extension_api.json`.<br><br>
124//!
125//! * **`double-precision`**
126//!
127//! Use `f64` instead of `f32` for the floating-point type [`real`][type@builtin::real]. Requires Godot to be compiled with the
128//! scons flag `precision=double`.<br><br>
129//!
130//! * **`experimental-godot-api`**
131//!
132//! Access to `godot::classes` APIs that Godot marks "experimental". These are under heavy development and may change at any time.
133//! If you opt in to this feature, expect breaking changes at compile and runtime.<br><br>
134//!
135//! _Rust functionality toggles:_
136//!
137//! * **`lazy-function-tables`**
138//!
139//! Instead of loading all engine function pointers at startup, load them lazily on first use. This reduces startup time and RAM usage, but
140//! incurs additional overhead in each FFI call. Also, you lose the guarantee that once the library has booted, all function pointers are
141//! truly available. Function calls may thus panic only at runtime, possibly in deeply nested code paths.
142//! This feature is not yet thread-safe and can thus not be combined with `experimental-threads`.<br><br>
143//!
144//! * **`experimental-threads`**
145//!
146//! Experimental threading support. This adds synchronization to access the user instance in `Gd<T>` and disables several single-thread checks.
147//! The safety aspects are not ironed out yet; there is a high risk of unsoundness at the moment.
148//! As this evolves, it is very likely that the API becomes stricter.<br><br>
149//!
150//! * **`experimental-wasm`**
151//!
152//! Support for WebAssembly exports is still a work-in-progress and is not yet well tested. This feature is in place for users
153//! to explicitly opt in to any instabilities or rough edges that may result.
154//!
155//! Please read [Export to Web](https://godot-rust.github.io/book/toolchain/export-web.html) in the book.
156//!
157//! By default, Wasm threads are enabled and require the flag `"-C", "link-args=-pthread"` in the `wasm32-unknown-unknown` target.
158//! This must be kept in sync with Godot's Web export settings (threading support enabled). To disable it, use **additionally* the feature
159//! `experimental-wasm-nothreads`.
160//!
161//! It is recommended to use this feature in combination with `lazy-function-tables` to reduce the size of the generated Wasm binary.<br><br>
162//!
163//! * **`experimental-wasm-nothreads`**
164//!
165//! Requires the `experimental-wasm` feature. Disables threading support for WebAssembly exports. This needs to be kept in sync with
166//! Godot's Web export setting (threading support disabled), and must _not_ use the `"-C", "link-args=-pthread"` flag in the
167//! `wasm32-unknown-unknown` target.<br><br>
168//!
169//! * **`codegen-rustfmt`**
170//!
171//! Use rustfmt to format generated binding code. Because rustfmt is so slow, this is detrimental to initial compile time.
172//! Without it, we use a lightweight and fast custom formatter to enable basic human readability.<br><br>
173//!
174//! * **`register-docs`**
175//!
176//! Generates documentation for your structs from your Rust documentation.
177//! Documentation is visible in Godot via `F1` -> searching for that class.
178//! This feature requires at least Godot 4.3.
179//! See also: [`#[derive(GodotClass)]`](register/derive.GodotClass.html#documentation)
180//!
181//! _Safeguards:_
182//!
183//! See [Safeguard levels](#safeguard-levels).
184//!
185//! * **`safeguards-dev-balanced`**
186//!
187//! For the `dev` Cargo profile, use the **balanced** safeguard level instead of the default strict level.<br><br>
188//!
189//! * **`safeguards-release-disengaged`**
190//!
191//! For the `release` Cargo profile, use the **disengaged** safeguard level instead of the default balanced level.
192//!
193//! _Third-party integrations:_
194//!
195//! * **`serde`**
196//!
197//! Implement the [serde](https://serde.rs/) traits `Serialize` and `Deserialize` traits for certain built-in types.
198//! The serialized representation underlies **no stability guarantees** and may change at any time, even without a SemVer-breaking change.
199//!
200
201#![doc(
202 html_logo_url = "https://raw.githubusercontent.com/godot-rust/assets/master/gdext/ferris.svg"
203)]
204
205#[cfg(doc)]
206pub mod __docs;
207
208// ----------------------------------------------------------------------------------------------------------------------------------------------
209// Validations
210
211// Many validations are moved to godot-ffi. #[cfg]s are not emitted in this crate, so move checks for those up to godot-core.
212
213#[cfg(all(target_family = "wasm", not(feature = "experimental-wasm")))]
214compile_error!(
215 "Wasm target requires opt-in via `experimental-wasm` Cargo feature;\n\
216 keep in mind that this is work in progress."
217);
218
219// See also https://github.com/godotengine/godot/issues/86346.
220// Could technically be moved to godot-codegen to reduce time-to-failure slightly, but would scatter validations even more.
221#[cfg(all(
222 feature = "double-precision",
223 not(feature = "api-custom"),
224 not(feature = "api-custom-json")
225))]
226compile_error!(
227 "The feature `double-precision` currently requires `api-custom` or `api-custom-json` due to incompatibilities in the GDExtension API JSON. \
228See: https://github.com/godotengine/godot/issues/86346"
229);
230
231// On non-Emscripen targets, wasm-ld will insert a call to __wasm_call_ctors (which calls all constructors) to the start all exported functions,
232// if it detects that __wasm_call_ctors is never called and not exported. This could cause constructors to run multiple times.
233// Emscripen should always export __wasm_call_ctors and call it at runtime.
234// See https://github.com/godot-rust/gdext/pull/1476 for more info and links.
235#[cfg(all(target_family = "wasm", not(target_os = "emscripten")))]
236compile_error!("Wasm targets not using Emscripten are not supported.");
237
238// ----------------------------------------------------------------------------------------------------------------------------------------------
239// Modules
240
241#[doc(hidden)]
242pub use godot_core::possibly_docs as docs;
243#[doc(hidden)]
244pub use godot_core::sys;
245#[doc(inline)]
246pub use godot_core::{builtin, classes, global, obj, task, tools};
247
248/// Entry point and global init/shutdown of the library.
249pub mod init {
250 pub use godot_core::init::*;
251 // Re-exports
252 pub use godot_macros::gdextension;
253}
254
255/// Meta-information about Godot types, their properties and conversions between them.
256pub mod meta {
257 // Submodules.
258 // Derive macro (moved from `register`).
259 pub use godot_core::meta::ClassId;
260 #[doc(hidden)]
261 pub use godot_core::meta::arg_into_owned;
262 #[cfg(feature = "__trace")]
263 #[doc(hidden)]
264 pub use godot_core::meta::trace;
265 // Argument conversions that stay in flat `meta`.
266 pub use godot_core::meta::{AsArg, ObjectArg, ToArg, owned_into_arg, ref_to_arg};
267 // Hidden internal items for proc-macros and generated code.
268 #[doc(hidden)]
269 pub use godot_core::meta::{CallContext, Signature, ensure_func_bounds};
270 #[cfg(feature = "__trace")]
271 #[doc(hidden)]
272 pub use godot_core::meta::{CowArg, FfiArg};
273 // Type traits.
274 pub use godot_core::meta::{
275 Element, GodotImmutable, GodotType, PackedElement, element_variant_type,
276 };
277 // Conversion traits.
278 pub use godot_core::meta::{EngineFromGodot, EngineToGodot, FromGodot, GodotConvert, ToGodot};
279 // Range utilities.
280 pub use godot_core::meta::{SignedRange, wrapped};
281 #[doc(inline)]
282 pub use godot_core::meta::{conv, error, inspect, shape};
283 pub use godot_macros::GodotConvert;
284}
285
286/// Runtime types for working with signals: connecting, emitting, and handling.
287pub mod signal {
288 pub use godot_core::obj::signal::re_export::*;
289}
290
291/// Register/export Rust symbols to Godot: classes, methods, enums...
292pub mod register {
293 #[cfg(feature = "__codegen-full")]
294 pub use godot_core::registry::RpcConfig;
295 pub use godot_macros::{GodotClass, godot_api, godot_dyn};
296
297 /// Register Rust fields as Godot properties.
298 pub mod property {
299 pub use godot_core::registry::property::*;
300 // Derive macros for property traits.
301 pub use godot_macros::{Export, Var};
302 }
303
304 #[doc(inline)]
305 pub use godot_core::registry::info;
306
307 /// Re-exports used by proc-macro API.
308 #[doc(hidden)]
309 pub mod private {
310 #[cfg(feature = "__codegen-full")]
311 pub use godot_core::registry::class::auto_register_rpcs;
312 pub use godot_core::registry::godot_register_wrappers::*;
313 pub use godot_core::registry::{constant, method};
314 }
315}
316
317/// Testing facilities (unstable).
318#[doc(hidden)]
319pub mod test {
320 pub use godot_macros::{bench, itest};
321}
322
323#[doc(hidden)]
324pub use godot_core::__deprecated;
325#[doc(hidden)]
326pub use godot_core::private;
327
328/// Often-imported symbols.
329pub mod prelude;