forked from godot-rust/gdnative
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instance.rs
628 lines (568 loc) · 19.6 KB
/
instance.rs
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
use std::ffi::{self, CStr};
use std::ptr::NonNull;
use crate::core_types::{
FromVariant, FromVariantError, GodotString, OwnedToVariant, ToVariant, Variant,
};
use crate::export::user_data::{Map, MapMut, MapOwned, UserData};
use crate::export::{class_registry, emplace, NativeClass};
use crate::object::bounds::{
AssumeSafeLifetime, LifetimeConstraint, RefImplBound, SafeAsRaw, SafeDeref,
};
use crate::object::memory::{ManuallyManaged, RefCounted};
use crate::object::ownership::{NonUniqueOwnership, Ownership, Shared, ThreadLocal, Unique};
use crate::object::{GodotObject, Instanciable, QueueFree, RawObject, Ref, TRef};
use crate::private::{get_api, ReferenceCountedClassPlaceholder};
/// A persistent reference to a GodotObject with a rust NativeClass attached.
///
/// `Instance`s can be worked on directly using `map` and `map_mut` if the base object is
/// reference-counted. Otherwise, use `assume_safe` to obtain a temporary `TInstance`.
///
/// See the type-level documentation on `Ref` for more information on typed thread accesses.
#[derive(Debug)]
pub struct Instance<T: NativeClass, Own: Ownership = Shared> {
owner: Ref<T::Base, Own>,
script: T::UserData,
}
/// A reference to a GodotObject with a rust NativeClass attached that is assumed safe during
/// a certain lifetime.
///
/// See the type-level documentation on `Ref` for more information on typed thread accesses.
#[derive(Debug)]
pub struct TInstance<'a, T: NativeClass, Own: Ownership = Shared> {
owner: TRef<'a, T::Base, Own>,
script: T::UserData,
}
impl<T: NativeClass> Instance<T, Unique> {
/// Creates a `T::Base` with the script `T` attached. Both `T::Base` and `T` must have zero
/// argument constructors.
///
/// If `T::Base` is manually-managed, then the resulting `Instance` must be passed to
/// the engine or manually freed with `Instance::free`. Otherwise, the base object will be
/// leaked.
///
/// Must be called after the library is initialized.
#[inline]
#[allow(clippy::new_without_default)]
pub fn new() -> Self
where
T::Base: Instanciable,
{
Self::maybe_emplace(None)
}
/// Creates a `T::Base` with a given instance of the script `T` attached. `T::Base` must
/// have a zero-argument constructor.
///
/// This may be used to create instances of scripts that do not have zero-argument
/// constructors:
///
/// ```ignore
/// // This type does not have a zero-argument constructor. As a result, `Instance::new`
/// // will panic and `Foo.new` from GDScript will result in errors when the object is used.
/// #[derive(NativeScript)]
/// #[inherit(Reference)]
/// #[no_constructor]
/// struct MyIntVector(i64, i64);
///
/// #[methods]
/// impl MyIntVector {
/// // - snip -
/// }
///
/// // With `Instance::emplace`, however, we can expose "constructors" from a factory
/// // auto-load for our script type.
/// #[derive(NativeScript)]
/// #[inherit(Node)]
/// #[user_data(Aether<Self>)]
/// struct MyIntVectorFactory;
///
/// #[methods]
/// impl MyIntVectorFactory {
/// #[export]
/// fn make(&self, _owner: &Node, x: i64, y: i64) -> Instance<MyIntVector, Unique> {
/// Instance::emplace(MyIntVector(x, y))
/// }
/// }
/// ```
///
/// If `T::Base` is manually-managed, then the resulting `Instance` must be passed to
/// the engine or manually freed with `Instance::free`. Otherwise, the base object will be
/// leaked.
///
/// Must be called after the library is initialized.
#[inline]
pub fn emplace(script: T) -> Self
where
T::Base: Instanciable,
{
Self::maybe_emplace(Some(script))
}
fn maybe_emplace(script: Option<T>) -> Self
where
T::Base: Instanciable,
{
let gd_api = get_api();
let nativescript_methods = crate::private::NativeScriptMethodTable::get(gd_api);
assert_ne!(
std::ptr::null(),
nativescript_methods.set_class_name,
"NativeScript::set_class_name must be available"
);
assert_ne!(
std::ptr::null(),
nativescript_methods.set_library,
"NativeScript::set_library must be available"
);
assert_ne!(
std::ptr::null(),
nativescript_methods.new,
"NativeScript::new must be available"
);
let native_script = unsafe {
let class_name = CStr::from_bytes_with_nul_unchecked(b"NativeScript\0");
let ctor = (gd_api.godot_get_class_constructor)(class_name.as_ptr()).unwrap();
let native_script =
NonNull::new(ctor()).expect("NativeScript constructor should not return null");
let native_script =
RawObject::<ReferenceCountedClassPlaceholder>::from_sys_ref_unchecked(
native_script,
);
native_script.init_ref_count();
native_script
};
// `set_library` should be called before `set_class_name` to trigger class registration
// before trying to fetch the class name, in case the first NativeScript instance of this
// library is being constructed from Rust.
let mut args: [*const ffi::c_void; 1] = [crate::private::get_gdnative_library_sys()];
unsafe {
(gd_api.godot_method_bind_ptrcall)(
nativescript_methods.set_library,
native_script.sys().as_ptr(),
args.as_mut_ptr(),
std::ptr::null_mut(),
)
};
let script_class_name = class_registry::class_name::<T>()
.map(GodotString::from)
.unwrap_or_else(|| {
panic!(
"`{type_name}` must be registered before it can be used; call `handle.add_class::<{type_name}>()` in your `nativescript_init` callback",
type_name = std::any::type_name::<T>(),
);
});
let mut args: [*const ffi::c_void; 1] = [script_class_name.sys() as *const _];
unsafe {
(gd_api.godot_method_bind_ptrcall)(
nativescript_methods.set_class_name,
native_script.sys().as_ptr(),
args.as_mut_ptr(),
std::ptr::null_mut(),
);
}
if let Some(script) = script {
emplace::place(script); // Are there side effects?
}
let mut args: [*const sys::godot_variant; 0] = [];
let variant = unsafe {
(gd_api.godot_method_bind_call)(
nativescript_methods.new,
native_script.sys().as_ptr(),
args.as_mut_ptr(),
0,
std::ptr::null_mut(),
)
};
assert!(
emplace::take::<T>().is_none(), // Are there side effects?
"emplacement value should be taken by the constructor wrapper (this is a bug in the bindings)",
);
let variant = Variant::from_sys(variant);
let owner = unsafe {
variant
.to_object::<T::Base>()
.expect("the engine should return a base object of the correct type")
.assume_unique()
};
let script_ptr = unsafe { (gd_api.godot_nativescript_get_userdata)(owner.sys()) };
assert_ne!(
std::ptr::null(),
script_ptr,
"script instance should not be null (did the constructor fail?)"
);
let script = unsafe { T::UserData::clone_from_user_data_unchecked(script_ptr) };
unsafe {
debug_assert!(native_script.unref_and_free_if_last());
}
Instance { owner, script }
}
}
impl<T: NativeClass, Own: Ownership> Instance<T, Own> {
/// Returns the base object, dropping the script wrapper.
#[inline]
pub fn into_base(self) -> Ref<T::Base, Own> {
self.owner
}
/// Returns the script wrapper.
#[inline]
pub fn into_script(self) -> T::UserData {
self.script
}
/// Returns the base object and the script wrapper.
#[inline]
pub fn decouple(self) -> (Ref<T::Base, Own>, T::UserData) {
(self.owner, self.script)
}
/// Returns a reference to the base object.
#[inline]
pub fn base(&self) -> &Ref<T::Base, Own> {
&self.owner
}
/// Returns a reference to the script wrapper.
#[inline]
pub fn script(&self) -> &T::UserData {
&self.script
}
/// Convert to a nullable raw pointer. Used for AsArg.
pub(super) fn as_base_ptr(&self) -> *mut sys::godot_object {
self.owner.as_ptr()
}
}
impl<T: NativeClass, Own: Ownership> Instance<T, Own>
where
RefImplBound: SafeAsRaw<<T::Base as GodotObject>::Memory, Own>,
{
/// Try to downcast `Ref<T::Base, Own>` to `Instance<T>`, without changing the reference
/// count if reference-counted.
///
/// # Errors
///
/// Returns the original `Ref` if the cast failed.
#[inline]
pub fn try_from_base(owner: Ref<T::Base, Own>) -> Result<Self, Ref<T::Base, Own>> {
let user_data = match try_get_user_data_ptr::<T>(owner.as_raw()) {
Some(user_data) => user_data,
None => return Err(owner),
};
let script = unsafe { T::UserData::clone_from_user_data_unchecked(user_data) };
Ok(Instance { owner, script })
}
/// Try to downcast `Ref<T::Base, Own>` to `Instance<T>`, without changing the reference
/// count if reference-counted. Shorthand for `Self::try_from_base().ok()`.
#[inline]
pub fn from_base(owner: Ref<T::Base, Own>) -> Option<Self> {
Self::try_from_base(owner).ok()
}
}
impl<T: NativeClass, Own: Ownership> Instance<T, Own>
where
RefImplBound: SafeDeref<<T::Base as GodotObject>::Memory, Own>,
{
/// Calls a function with a NativeClass instance and its owner, and returns its return
/// value. Can be used on reference counted types for multiple times.
#[inline]
pub fn map<F, U>(&self, op: F) -> Result<U, <T::UserData as Map>::Err>
where
T::UserData: Map,
F: FnOnce(&T, TRef<'_, T::Base, Own>) -> U,
{
self.script.map(|script| op(script, self.owner.as_ref()))
}
/// Calls a function with a NativeClass instance and its owner, and returns its return
/// value. Can be used on reference counted types for multiple times.
#[inline]
pub fn map_mut<F, U>(&self, op: F) -> Result<U, <T::UserData as MapMut>::Err>
where
T::UserData: MapMut,
F: FnOnce(&mut T, TRef<'_, T::Base, Own>) -> U,
{
self.script
.map_mut(|script| op(script, self.owner.as_ref()))
}
/// Calls a function with a NativeClass instance and its owner, and returns its return
/// value. Can be used on reference counted types for multiple times.
#[inline]
pub fn map_owned<F, U>(&self, op: F) -> Result<U, <T::UserData as MapOwned>::Err>
where
T::UserData: MapOwned,
F: FnOnce(T, TRef<'_, T::Base, Own>) -> U,
{
self.script
.map_owned(|script| op(script, self.owner.as_ref()))
}
}
/// Methods for instances with manually-managed base classes.
impl<T: NativeClass> Instance<T, Shared> {
/// Assume that `self` is safe to use.
///
/// This is *not* guaranteed to be a no-op at runtime.
///
/// # Safety
///
/// It's safe to call `assume_safe` only if the constraints of `Ref::assume_safe`
/// are satisfied for the base object.
#[inline]
pub unsafe fn assume_safe<'a, 'r>(&'r self) -> TInstance<'a, T, Shared>
where
AssumeSafeLifetime<'a, 'r>: LifetimeConstraint<<T::Base as GodotObject>::Memory>,
{
TInstance {
owner: self.owner.assume_safe(),
script: self.script.clone(),
}
}
}
impl<T: NativeClass> Instance<T, Shared>
where
T::Base: GodotObject<Memory = ManuallyManaged>,
{
/// Returns `true` if the pointer currently points to a valid object of the correct type.
/// **This does NOT guarantee that it's safe to use this pointer.**
///
/// # Safety
///
/// This thread must have exclusive access to the object during the call.
#[inline]
#[allow(clippy::trivially_copy_pass_by_ref)]
pub unsafe fn is_instance_sane(&self) -> bool {
self.owner.is_instance_sane()
}
}
impl<T: NativeClass> Instance<T, Unique>
where
T::Base: GodotObject<Memory = ManuallyManaged>,
{
/// Frees the base object and user-data wrapper.
///
/// Same as `self.into_base().free()`.
#[inline]
pub fn free(self) {
self.into_base().free()
}
}
impl<T: NativeClass> Instance<T, Unique>
where
T::Base: GodotObject<Memory = ManuallyManaged> + QueueFree,
{
/// Queues the base object and user-data wrapper for deallocation in the near future.
/// This should be preferred to `free` for `Node`s.
///
/// Same as `self.into_base().queue_free()`.
#[inline]
pub fn queue_free(self) {
self.into_base().queue_free()
}
}
impl<T: NativeClass> Instance<T, Unique> {
/// Coverts into a `Shared` instance.
#[inline]
pub fn into_shared(self) -> Instance<T, Shared> {
Instance {
owner: self.owner.into_shared(),
script: self.script,
}
}
}
impl<T: NativeClass> Instance<T, Unique>
where
T::Base: GodotObject<Memory = RefCounted>,
{
/// Coverts into a `ThreadLocal` instance.
#[inline]
pub fn into_thread_local(self) -> Instance<T, ThreadLocal> {
Instance {
owner: self.owner.into_thread_local(),
script: self.script,
}
}
}
impl<T: NativeClass> Instance<T, Shared> {
/// Assume that `self` is the unique reference to the underlying base object.
///
/// This is guaranteed to be a no-op at runtime if `debug_assertions` is disabled. Runtime
/// sanity checks may be added in debug builds to help catch bugs.
///
/// # Safety
///
/// Calling `assume_unique` when `self` isn't the unique reference is instant undefined
/// behavior. This is a much stronger assumption than `assume_safe` and should be used with
/// care.
#[inline]
pub unsafe fn assume_unique(self) -> Instance<T, Unique> {
Instance {
owner: self.owner.assume_unique(),
script: self.script,
}
}
}
impl<T: NativeClass> Instance<T, Shared>
where
T::Base: GodotObject<Memory = RefCounted>,
{
/// Assume that all references to the underlying object is local to the current thread.
///
/// This is guaranteed to be a no-op at runtime.
///
/// # Safety
///
/// Calling `assume_thread_local` when there are references on other threads is instant
/// undefined behavior. This is a much stronger assumption than `assume_safe` and should
/// be used with care.
#[inline]
pub unsafe fn assume_thread_local(self) -> Instance<T, ThreadLocal> {
Instance {
owner: self.owner.assume_thread_local(),
script: self.script,
}
}
}
impl<'a, T: NativeClass, Own: Ownership> TInstance<'a, T, Own> {
/// Returns a reference to the base object with the same lifetime.
#[inline]
pub fn base(&self) -> TRef<'a, T::Base, Own> {
self.owner
}
/// Returns a reference to the script wrapper.
#[inline]
pub fn script(&self) -> &T::UserData {
&self.script
}
/// Try to downcast `TRef<'a, T::Base, Own>` to `TInstance<T>`.
#[inline]
pub fn try_from_base(owner: TRef<'a, T::Base, Own>) -> Option<Self> {
let user_data = try_get_user_data_ptr::<T>(owner.as_raw())?;
unsafe { Some(Self::from_raw_unchecked(owner, user_data)) }
}
/// Pairs an `owner` and `user_data` without checking validity. Internal interface.
#[doc(hidden)]
#[inline]
pub unsafe fn from_raw_unchecked(
owner: TRef<'a, T::Base, Own>,
user_data: *mut libc::c_void,
) -> Self {
let script = T::UserData::clone_from_user_data_unchecked(user_data);
TInstance { owner, script }
}
/// Convert to a nullable raw pointer. Used for AsArg.
pub(super) fn as_base_ptr(&self) -> *mut sys::godot_object {
self.owner.as_ptr()
}
}
impl<'a, T: NativeClass, Own: NonUniqueOwnership> TInstance<'a, T, Own> {
/// Persists this into a persistent `Instance` with the same thread access, without cloning
/// the userdata wrapper.
///
/// This is only available for non-`Unique` accesses.
#[inline]
pub fn claim(self) -> Instance<T, Own> {
Instance {
owner: self.owner.claim(),
script: self.script,
}
}
}
/// Methods for instances with reference-counted base classes.
impl<'a, T: NativeClass, Own: Ownership> TInstance<'a, T, Own>
where
T::Base: GodotObject,
{
/// Calls a function with a NativeClass instance and its owner, and returns its return
/// value.
#[inline]
pub fn map<F, U>(&self, op: F) -> Result<U, <T::UserData as Map>::Err>
where
T::UserData: Map,
F: FnOnce(&T, TRef<'_, T::Base, Own>) -> U,
{
self.script.map(|script| op(script, self.owner))
}
/// Calls a function with a NativeClass instance and its owner, and returns its return
/// value.
#[inline]
pub fn map_mut<F, U>(&self, op: F) -> Result<U, <T::UserData as MapMut>::Err>
where
T::UserData: MapMut,
F: FnOnce(&mut T, TRef<'_, T::Base, Own>) -> U,
{
self.script.map_mut(|script| op(script, self.owner))
}
/// Calls a function with a NativeClass instance and its owner, and returns its return
/// value.
#[inline]
pub fn map_owned<F, U>(&self, op: F) -> Result<U, <T::UserData as MapOwned>::Err>
where
T::UserData: MapOwned,
F: FnOnce(T, TRef<'_, T::Base, Own>) -> U,
{
self.script.map_owned(|script| op(script, self.owner))
}
}
impl<T, Own: Ownership> Clone for Instance<T, Own>
where
T: NativeClass,
Ref<T::Base, Own>: Clone,
{
#[inline]
fn clone(&self) -> Self {
Instance {
owner: self.owner.clone(),
script: self.script.clone(),
}
}
}
impl<'a, T, Own: Ownership> Clone for TInstance<'a, T, Own>
where
T: NativeClass,
{
#[inline]
fn clone(&self) -> Self {
TInstance {
owner: self.owner,
script: self.script.clone(),
}
}
}
impl<T, Own: Ownership> ToVariant for Instance<T, Own>
where
T: NativeClass,
Ref<T::Base, Own>: ToVariant,
{
#[inline]
fn to_variant(&self) -> Variant {
self.owner.to_variant()
}
}
impl<T> OwnedToVariant for Instance<T, Unique>
where
T: NativeClass,
{
#[inline]
fn owned_to_variant(self) -> Variant {
self.into_base().owned_to_variant()
}
}
impl<T> FromVariant for Instance<T, Shared>
where
T: NativeClass,
T::Base: GodotObject<Memory = RefCounted>,
{
#[inline]
fn from_variant(variant: &Variant) -> Result<Self, FromVariantError> {
let owner = Ref::<T::Base, Shared>::from_variant(variant)?;
Self::from_base(owner).ok_or(FromVariantError::InvalidInstance {
expected: class_registry::class_name_or_default::<T>(),
})
}
}
fn try_get_user_data_ptr<T: NativeClass>(owner: &RawObject<T::Base>) -> Option<*mut libc::c_void> {
unsafe {
let api = get_api();
let owner_ptr = owner.sys().as_ptr();
let type_tag = (api.godot_nativescript_get_type_tag)(owner_ptr);
if type_tag.is_null() {
return None;
}
if !crate::export::type_tag::check::<T>(type_tag) {
return None;
}
Some((api.godot_nativescript_get_userdata)(owner_ptr))
}
}