godot-core 0.5.1

Internal crate used by godot-rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*
 * Copyright (c) godot-rust; Bromeon and contributors.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use crate::builtin::{Array, Variant};
use crate::meta;
use crate::meta::error::{ConvertError, ErrorKind, FromFfiError};
use crate::meta::shape::GodotShape;
use crate::meta::{Element, FromGodot, GodotConvert, GodotNullableType, GodotType, ToGodot};
use crate::registry::info::ParamMetadata;

// The following ToGodot/FromGodot/Convert impls are auto-generated for each engine type, co-located with their definitions:
// - enum
// - const/mut pointer to native struct

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Option<T>

impl<T: GodotNullableType> GodotType for Option<T> {
    type Ffi = T::Ffi;
    type ToFfi<'f> = T::ToFfi<'f>;

    fn to_ffi(&self) -> Self::ToFfi<'_> {
        self.as_ref()
            .map(|t| t.to_ffi())
            .unwrap_or_else(T::ffi_null_ref)
    }

    fn into_ffi(self) -> Self::Ffi {
        self.map(|t| t.into_ffi()).unwrap_or_else(T::ffi_null)
    }

    fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
        if T::ffi_is_null(&ffi) {
            return Ok(None);
        }

        GodotType::try_from_ffi(ffi).map(Some)
    }

    fn from_ffi(ffi: Self::Ffi) -> Self {
        if T::ffi_is_null(&ffi) {
            return None;
        }

        Some(GodotType::from_ffi(ffi))
    }

    // Only relevant for object types T.
    fn as_object_arg(&self) -> meta::ObjectArg<'_> {
        match self {
            Some(inner) => inner.as_object_arg(),
            None => meta::ObjectArg::null(),
        }
    }
}

impl<T> GodotConvert for Option<T>
where
    T: GodotConvert,
    Option<T::Via>: GodotType,
{
    type Via = Option<T::Via>;

    fn godot_shape() -> GodotShape {
        // Option<Gd<T>> is nullable, so param metadata will return NONE instead of OBJECT_IS_REQUIRED.
        match T::godot_shape() {
            GodotShape::Class {
                class_id, heritage, ..
            } => GodotShape::Class {
                class_id,
                heritage,
                is_nullable: true,
            },
            other => other,
        }
    }
}

impl<T> ToGodot for Option<T>
where
    // Currently limited to holding objects -> needed to establish to_godot() relation T::to_godot() = Option<&T::Via>.
    T: ToGodot<Pass = meta::ByObject>,
    // T::Via must be a Godot nullable type (to support the None case).
    T::Via: GodotNullableType,
    // Previously used bound, not needed right now but don't remove: Option<T::Via>: GodotType,
{
    // Basically ByRef, but allows Option<T> -> Option<&T::Via> conversion.
    type Pass = meta::ByOption<T::Via>;

    fn to_godot(&self) -> Option<&T::Via> {
        self.as_ref().map(T::to_godot)
    }

    fn to_godot_owned(&self) -> Option<T::Via> {
        self.as_ref().map(T::to_godot_owned)
    }

    fn to_variant(&self) -> Variant {
        match self {
            Some(inner) => inner.to_variant(),
            None => Variant::nil(),
        }
    }
}

impl<T: FromGodot> FromGodot for Option<T>
where
    Option<T::Via>: GodotType,
{
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        match via {
            Some(via) => T::try_from_godot(via).map(Some),
            None => Ok(None),
        }
    }

    fn from_godot(via: Self::Via) -> Self {
        via.map(T::from_godot)
    }

    fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError> {
        // Note: this forwards to T::Via, not Self::Via (= Option<T>::Via).
        // For Option<T>, there is a blanket impl GodotType, so case differentiations are not possible.
        if T::Via::qualifies_as_special_none(variant) {
            return Ok(None);
        }

        if variant.is_nil() {
            return Ok(None);
        }

        let value = T::try_from_variant(variant)?;
        Ok(Some(value))
    }

    fn from_variant(variant: &Variant) -> Self {
        if variant.is_nil() {
            return None;
        }

        Some(T::from_variant(variant))
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Scalars

macro_rules! impl_godot_scalar {
    ($T:ty as $Via:ty, $err:path, $param_metadata:expr_2021) => {
        impl GodotType for $T {
            type Ffi = $Via;
            type ToFfi<'f> = $Via;

            fn to_ffi(&self) -> Self::ToFfi<'_> {
                (*self).into()
            }

            fn into_ffi(self) -> Self::Ffi {
                self.into()
            }

            fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
                Self::try_from(ffi).map_err(|_rust_err| {
                    // rust_err is something like "out of range integral type conversion attempted", not adding extra information.
                    // TODO consider passing value into error message, but how thread-safely? don't eagerly convert to string.
                    $err.into_error(ffi)
                })
            }

            impl_godot_scalar!(@shared_fns; $Via, $param_metadata);
        }

        // For integer types, we can validate the conversion.
        impl Element for $T {
            fn debug_validate_elements(array: &Array<Self>) -> Result<(), ConvertError> {
                array.debug_validate_int_elements()
            }
        }

        impl_godot_scalar!(@shared_traits; $T);
    };

    ($T:ty as $Via:ty, $param_metadata:expr_2021; lossy) => {
        impl GodotType for $T {
            type Ffi = $Via;
            type ToFfi<'f> = $Via;

            fn to_ffi(&self) -> Self::ToFfi<'_> {
                *self as $Via
            }

            fn into_ffi(self) -> Self::Ffi {
                self as $Via
            }

            fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
                Ok(ffi as $T)
            }

            impl_godot_scalar!(@shared_fns; $Via, $param_metadata);
        }

        // For f32, conversion from f64 is lossy but will always succeed. Thus no debug validation needed.
        impl Element for $T {}

        impl_godot_scalar!(@shared_traits; $T);
    };

    (@shared_fns; $Via:ty, $param_metadata:expr_2021) => {
        fn default_metadata() -> ParamMetadata {
            $param_metadata
        }
    };

    (@shared_traits; $T:ty) => {
        impl GodotConvert for $T {
            type Via = $T;

            fn godot_shape() -> GodotShape {
                GodotShape::of_builtin::<$T>()
            }
        }

        impl ToGodot for $T {
            type Pass = meta::ByValue;

            fn to_godot(&self) -> Self::Via {
               *self
            }
        }

        impl FromGodot for $T {
            fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
                Ok(via)
            }
        }
    };
}

// `GodotType` for these three is implemented in `godot-core/src/builtin/variant/impls.rs`.
meta::impl_godot_as_self!(bool: ByValue);
meta::impl_godot_as_self!(i64: ByValue);
meta::impl_godot_as_self!(f64: ByValue);
meta::impl_godot_as_self!((): ByValue);

// Also implements Element.
impl_godot_scalar!(i8 as i64, FromFfiError::I8, ParamMetadata::INT_IS_INT8);
impl_godot_scalar!(u8 as i64, FromFfiError::U8, ParamMetadata::INT_IS_UINT8);
impl_godot_scalar!(i16 as i64, FromFfiError::I16, ParamMetadata::INT_IS_INT16);
impl_godot_scalar!(u16 as i64, FromFfiError::U16, ParamMetadata::INT_IS_UINT16);
impl_godot_scalar!(i32 as i64, FromFfiError::I32, ParamMetadata::INT_IS_INT32);
impl_godot_scalar!(u32 as i64, FromFfiError::U32, ParamMetadata::INT_IS_UINT32);
impl_godot_scalar!(f32 as f64, ParamMetadata::REAL_IS_FLOAT; lossy);

// ----------------------------------------------------------------------------------------------------------------------------------------------
// u64: manually implemented, to ensure that type is not altered during conversion.

impl GodotType for u64 {
    type Ffi = i64;
    type ToFfi<'f> = i64;

    fn to_ffi(&self) -> Self::ToFfi<'_> {
        *self as i64
    }

    fn into_ffi(self) -> Self::Ffi {
        self as i64
    }

    fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
        Ok(ffi as u64)
    }

    impl_godot_scalar!(@shared_fns; i64, ParamMetadata::INT_IS_UINT64);
}

impl GodotConvert for u64 {
    type Via = u64;

    fn godot_shape() -> GodotShape {
        GodotShape::of_builtin::<u64>()
    }
}

// u64 implements internal-only conversion traits for use in engine APIs and virtual methods.
impl meta::EngineToGodot for u64 {
    type Pass = meta::ByValue;

    fn engine_to_godot(&self) -> meta::ToArg<'_, Self::Via, Self::Pass> {
        *self
    }

    fn engine_to_variant(&self) -> Variant {
        Variant::from(*self as i64) // Treat as i64.
    }
}

impl meta::EngineFromGodot for u64 {
    fn engine_try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        Ok(via)
    }

    fn engine_try_from_variant(variant: &Variant) -> Result<Self, ConvertError> {
        variant.try_to::<i64>().map(|i| i as u64)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Collections

impl<T: Element> GodotConvert for Vec<T> {
    type Via = Array<T>;

    fn godot_shape() -> GodotShape {
        <Array<T> as GodotConvert>::godot_shape()
    }
}

impl<T: Element> ToGodot for Vec<T> {
    type Pass = meta::ByValue;

    fn to_godot(&self) -> Self::Via {
        Array::from(self.as_slice())
    }
}

impl<T: Element> FromGodot for Vec<T> {
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        Ok(via.iter_shared().collect())
    }
}

impl<T: Element, const LEN: usize> GodotConvert for [T; LEN] {
    type Via = Array<T>;

    fn godot_shape() -> GodotShape {
        <Array<T> as GodotConvert>::godot_shape()
    }
}

impl<T: Element, const LEN: usize> ToGodot for [T; LEN] {
    type Pass = meta::ByValue;

    fn to_godot(&self) -> Self::Via {
        Array::from(self)
    }
}

impl<T: Element, const LEN: usize> FromGodot for [T; LEN] {
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        let via_len = via.len(); // Caching this avoids an FFI call
        if via_len != LEN {
            let message =
                format!("Array<T> of length {via_len} cannot be stored in [T; {LEN}] Rust array");
            return Err(ConvertError::with_kind_value(
                ErrorKind::Custom(Some(message.into())),
                via,
            ));
        }

        let mut option_array = [const { None }; LEN];

        for (element, destination) in via.iter_shared().zip(&mut option_array) {
            *destination = Some(element);
        }

        let array = option_array.map(|some| {
            some.expect(
                "Elements were removed from Array during `iter_shared()`, this is not allowed",
            )
        });

        Ok(array)
    }
}

impl<T: Element> GodotConvert for &[T] {
    type Via = Array<T>;

    fn godot_shape() -> GodotShape {
        <Array<T> as GodotConvert>::godot_shape()
    }
}

impl<T: Element> ToGodot for &[T] {
    type Pass = meta::ByValue;

    fn to_godot(&self) -> Self::Via {
        Array::from(*self)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Raw pointers

// Following types used to be manually implemented, but are now covered by RawPtr<P>.
// - *mut *const u8
// - *mut i32
// - *mut f64
// - *mut u8
// - *const u8
//
// *const c_void: is used in some APIs like OpenXrApiExtension::transform_from_pose().
// *mut c_void: is used by ScriptExtension::instance_create().
//
// Other impls for raw pointers are generated for native structures and sys pointers (e.g. GDExtensionManager::load_extension_from_function).
// Some other pointer types are used by various other methods, see https://github.com/godot-rust/gdext/issues/677

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Tests for ToGodot/FromGodot missing impls
//
// Sanity check: comment-out ::godot::meta::ensure_func_bounds in func.rs, the 3 latter #[func] ones should fail.

/// Test that `u64` cannot be converted to variant.
///
/// ```compile_fail
/// # use godot::prelude::*;
/// let variant = 100u64.to_variant();  // Error: u64 does not implement ToGodot
/// ```
fn __doctest_u64() {}

/// Test that `*mut i32` cannot be converted to variant.
///
/// ```compile_fail
/// # use godot::prelude::*;
/// let ptr: *mut i32 = std::ptr::null_mut();
/// let variant = ptr.to_variant();  // Error: *mut i32 does not implement ToGodot
/// ```
fn __doctest_i32_ptr_to_variant() {}

/// Test that void-pointers cannot be converted from variant.
///
/// ```compile_fail
/// # use godot::prelude::*;
/// let variant = Variant::nil();
/// let ptr: *const std::ffi::c_void = variant.to();
/// ```
fn __doctest_void_ptr_from_variant() {}

/// Test that native struct pointers cannot be used as `#[func]` parameters.
///
/// ```compile_fail
/// # use godot::prelude::*;
/// # use godot::classes::native::AudioFrame;
/// #[derive(GodotClass)]
/// #[class(init)]
/// struct MyClass {}
///
/// #[godot_api]
/// impl MyClass {
///     #[func]
///     fn take_pointer(&self, ptr: *mut AudioFrame) {}
/// }
/// ```
fn __doctest_native_struct_pointer_param() {}

/// Test that native struct pointers cannot be used as `#[func]` return types.
///
/// ```compile_fail
/// # use godot::prelude::*;
/// # use godot::classes::native::AudioFrame;
/// #[derive(GodotClass)]
/// #[class(init)]
/// struct MyClass {}
///
/// #[godot_api]
/// impl MyClass {
///     #[func]
///     fn return_pointer(&self) -> *const AudioFrame {
///         std::ptr::null()
///     }
/// }
/// ```
fn __doctest_native_struct_pointer_return() {}

/// Test that `u64` cannot be returned from `#[func]`.
///
/// ```compile_fail
/// # use godot::prelude::*;
/// #[derive(GodotClass)]
/// #[class(init)]
/// struct MyClass {}
///
/// #[godot_api]
/// impl MyClass {
///     #[func]
///     fn return_pointer(&self) -> u64 { 123 }
/// }
/// ```
fn __doctest_u64_return() {}