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
use std::{mem, ptr};

use crate::raw::root::RED4ext as red;
use crate::types::{
    Bitfield, CName, Class, ClassFlags, ClassHandle, Enum, Function, GameEngine, GlobalFunction,
    PoolRef, RedArray, RedHashMap, Ref, RwSpinLockReadGuard, RwSpinLockWriteGuard,
    ScriptableSystem, Type,
};

/// The RTTI system containing information about all types in the game.
///
/// # Example
/// ```rust
/// use red4ext_rs::types::CName;
/// use red4ext_rs::RttiSystem;
///
/// fn rtti_example() {
///     let rtti = RttiSystem::get();
///     let class = rtti.get_class(CName::new("IScriptable")).unwrap();
///     for method in class.methods() {
///         // do something with the method
///     }
/// }
/// ```
#[repr(transparent)]
pub struct RttiSystem(red::CRTTISystem);

impl RttiSystem {
    /// Acquire a read lock on the RTTI system.
    #[inline]
    pub fn get<'a>() -> RwSpinLockReadGuard<'a, Self> {
        unsafe {
            let rtti = red::CRTTISystem_Get();
            let lock = &(*rtti).typesLock;
            RwSpinLockReadGuard::new(lock, ptr::NonNull::new_unchecked(rtti as _))
        }
    }

    /// Retrieve a class by its name.
    #[inline]
    pub fn get_class(&self, name: CName) -> Option<&Class> {
        let ty = unsafe { (self.vft().get_class)(self, name) };
        unsafe { ty.cast::<Class>().as_ref() }
    }

    /// Retrieve a type by its name.
    #[inline]
    pub fn get_type(&self, name: CName) -> Option<&Type> {
        let ty = unsafe { (self.vft().get_type)(self, name) };
        unsafe { ty.cast::<Type>().as_ref() }
    }

    /// Retrieve an enum by its name.
    #[inline]
    pub fn get_enum(&self, name: CName) -> Option<&Enum> {
        let ty = unsafe { (self.vft().get_enum)(self, name) };
        unsafe { ty.cast::<Enum>().as_ref() }
    }

    /// Retrieve a bitfield by its name.
    #[inline]
    pub fn get_bitfield(&self, name: CName) -> Option<&Bitfield> {
        let ty = unsafe { (self.vft().get_bitfield)(self, name) };
        unsafe { ty.cast::<Bitfield>().as_ref() }
    }

    /// Retrieve a function by its name.
    #[inline]
    pub fn get_function(&self, name: CName) -> Option<&Function> {
        let ty = unsafe { (self.vft().get_function)(self, name) };
        unsafe { ty.cast::<Function>().as_ref() }
    }

    /// Retrieve all native types and collect them into a [`RedArray`]`.
    #[inline]
    pub fn get_native_types(&self) -> RedArray<&Type> {
        let mut out = RedArray::default();
        unsafe {
            (self.vft().get_native_types)(self, &mut out as *mut _ as *mut RedArray<*mut Type>)
        };
        out
    }

    /// Retrieve all enums and collect them into a [`RedArray`]`.
    #[inline]
    pub fn get_enums(&self) -> RedArray<&Enum> {
        let mut out = RedArray::default();
        unsafe { (self.vft().get_enums)(self, &mut out as *mut _ as *mut RedArray<*mut Enum>) };
        out
    }

    /// Retrieve all bitfields and collect them into a [`RedArray`]`.
    #[inline]
    pub fn get_bitfields(&self, scripted_only: bool) -> RedArray<&Bitfield> {
        let mut out = RedArray::default();
        unsafe {
            (self.vft().get_bitfields)(
                self,
                &mut out as *mut _ as *mut RedArray<*mut Bitfield>,
                scripted_only,
            )
        };
        out
    }

    /// Retrieve all global functions and collect them into a [`RedArray`]`.
    #[inline]
    pub fn get_global_functions(&self) -> RedArray<&Function> {
        let mut out = RedArray::default();
        unsafe {
            (self.vft().get_global_functions)(
                self,
                &mut out as *mut _ as *mut RedArray<*mut Function>,
            )
        };
        out
    }

    /// Retrieve all instance methods and collect them into a [`RedArray`]`.
    #[inline]
    pub fn get_class_functions(&self) -> RedArray<&Function> {
        let mut out = RedArray::default();
        unsafe {
            (self.vft().get_class_functions)(
                self,
                &mut out as *mut _ as *mut RedArray<*mut Function>,
            )
        };
        out
    }

    /// Retrieve base class and its inheritors, optionally including abstract classes.
    #[inline]
    pub fn get_classes(&self, base: &Class, include_abstract: bool) -> RedArray<&Class> {
        let mut out = RedArray::default();
        unsafe {
            (self.vft().get_classes)(
                self,
                base,
                &mut out as *mut _ as *mut RedArray<*mut Class>,
                None,
                include_abstract,
            )
        };
        out
    }

    /// Retrieve derived classes, omitting base in the output.
    #[inline]
    pub fn get_derived_classes(&self, base: &Class) -> RedArray<&Class> {
        let mut out = RedArray::default();
        unsafe {
            (self.vft().get_derived_classes)(
                self,
                base,
                &mut out as *mut _ as *mut RedArray<*mut Class>,
            )
        };
        out
    }

    /// Retrieve a class by its script name.
    #[inline]
    pub fn get_class_by_script_name(&self, name: CName) -> Option<&Class> {
        let ty = unsafe { (self.vft().get_class_by_script_name)(self, name) };
        unsafe { ty.cast::<Class>().as_ref() }
    }

    /// Retrieve an enum by its script name.
    #[inline]
    pub fn get_enum_by_script_name(&self, name: CName) -> Option<&Enum> {
        let ty = unsafe { (self.vft().get_enum_by_script_name)(self, name) };
        unsafe { ty.cast::<Enum>().as_ref() }
    }

    /// Retrieve a reference to a map of all types by name.
    #[inline]
    pub fn type_map(&self) -> &RedHashMap<CName, &Type> {
        unsafe { &*(&self.0.types as *const _ as *const RedHashMap<CName, &Type>) }
    }

    /// Retrieve a reference to a map of all script to native name aliases.
    #[inline]
    pub fn script_to_native_map(&self) -> &RedHashMap<CName, CName> {
        unsafe { &*(&self.0.scriptToNative as *const _ as *const RedHashMap<CName, CName>) }
    }

    /// Retrieve a reference to a map of all native to script name aliases.
    #[inline]
    pub fn native_to_script_map(&self) -> &RedHashMap<CName, CName> {
        unsafe { &*(&self.0.nativeToScript as *const _ as *const RedHashMap<CName, CName>) }
    }

    /// Resolves a static method by its full name, which should be in the format `Class::Method`.
    #[inline]
    pub fn resolve_static_method_by_full_name(&self, full_name: &str) -> Option<&Function> {
        fn resolve_native(rtti: &RttiSystem, class: CName, method: CName) -> Option<&Function> {
            rtti.get_class(class)?
                .static_methods()
                .iter()
                .find(|m| m.as_function().name() == method)
                .map(|m| m.as_function())
        }

        // split on bytes rather than str to avoid inefficient UTF-8 scanning LLVM fails to
        // optimize away
        let mut parts = full_name.as_bytes().split(|&c| c == b':');
        let class = CName::from_bytes(parts.next()?);
        parts.next()?; // skip the separator
        let method = CName::from_bytes(parts.next()?);

        self.get_function(CName::new(full_name))
            .or_else(|| resolve_native(self, class, method))
    }

    /// Resolve the context required for a call to a static scripted method on specified class.
    /// Returns `None` if the class was not found in the RTTI system.
    pub fn resolve_static_context(&self, class: CName) -> Option<Ref<ScriptableSystem>> {
        let game = GameEngine::get().game_instance();
        let get_context = |class| Some(game.get_system(self.get_class(class)?.as_type()));
        let ctx = get_context(class)?;
        if ctx.is_null() {
            get_context(CName::new("cpPlayerSystem"))
        } else {
            Some(ctx)
        }
    }

    #[inline]
    fn vft(&self) -> &RttiSystemVft {
        unsafe { &*(self.0._base.vtable_ as *const RttiSystemVft) }
    }
}

/// The RTTI system containing information about all types in the game.
/// This variant allows for modifying the RTTI system and locks it for exclusive access.
#[repr(transparent)]
pub struct RttiSystemMut(red::CRTTISystem);

impl RttiSystemMut {
    /// Acquire a write lock on the RTTI system. You should be careful not to hold the lock for
    /// too long, because interleaving reads and write operations can lead to deadlocks.
    #[inline]
    pub fn get() -> RwSpinLockWriteGuard<'static, Self> {
        unsafe {
            let rtti = red::CRTTISystem_Get();
            let lock = &(*rtti).typesLock;
            RwSpinLockWriteGuard::new(lock, ptr::NonNull::new_unchecked(rtti as _))
        }
    }

    /// Retrieve a mutable reference to a class by its name
    pub fn get_class(&mut self, name: CName) -> Option<&mut Class> {
        // implemented manually to avoid the game trying to obtain the type lock
        let (types, types_by_id, type_ids) = self.split_types();
        if let Some(ty) = types.get_mut(&name) {
            return ty.as_class_mut();
        }
        let &id = type_ids.get(&name)?;
        types_by_id.get_mut(&id)?.as_class_mut()
    }

    /// Register a new [`ClassHandle`] with the RTTI system.
    /// The handle can be obtained from
    /// [`NativeClass::new_handle`](crate::types::NativeClass::new_handle).
    pub fn register_class(&mut self, mut class: ClassHandle) {
        // implemented manually to avoid the game trying to obtain the type lock
        let id = unsafe { red::RTTIRegistrator::GetNextId() };
        self.type_map()
            .insert(class.as_ref().name(), class.as_mut().as_type_mut());
        self.type_by_id_map()
            .insert(id, class.as_mut().as_type_mut());
        self.type_id_map().insert(class.as_ref().name(), id);
    }

    /// Register a new [`GlobalFunction`] with the RTTI system.
    /// The function can be obtained from [`GlobalFunction::new`].
    #[inline]
    pub fn register_function(&mut self, function: PoolRef<GlobalFunction>) {
        unsafe { (self.vft().register_function)(self, &*function) }
        // RTTI takes ownership of it from now on
        mem::forget(function);
    }

    #[inline]
    fn type_map(&mut self) -> &mut RedHashMap<CName, &mut Type> {
        unsafe { &mut *(&mut self.0.types as *mut _ as *mut RedHashMap<CName, &mut Type>) }
    }

    #[inline]
    fn type_by_id_map(&mut self) -> &mut RedHashMap<u32, &mut Type> {
        unsafe { &mut *(&mut self.0.typesByAsyncId as *mut _ as *mut RedHashMap<u32, &mut Type>) }
    }

    #[inline]
    fn type_id_map(&mut self) -> &mut RedHashMap<CName, u32> {
        unsafe { &mut *(&mut self.0.typeAsyncIds as *mut _ as *mut RedHashMap<CName, u32>) }
    }

    #[inline]
    #[allow(clippy::type_complexity)]
    fn split_types(
        &mut self,
    ) -> (
        &mut RedHashMap<CName, &mut Type>,
        &mut RedHashMap<u32, &mut Type>,
        &mut RedHashMap<CName, u32>,
    ) {
        unsafe {
            (
                &mut *(&mut self.0.types as *mut _ as *mut RedHashMap<CName, &mut Type>),
                &mut *(&mut self.0.typesByAsyncId as *mut _ as *mut RedHashMap<u32, &mut Type>),
                &mut *(&mut self.0.typeAsyncIds as *mut _ as *mut RedHashMap<CName, u32>),
            )
        }
    }

    #[inline]
    fn vft(&self) -> &RttiSystemVft {
        unsafe { &*(self.0._base.vtable_ as *const RttiSystemVft) }
    }
}

#[repr(C)]
struct RttiSystemVft {
    get_type: unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Type,
    get_type_by_async_id:
        unsafe extern "fastcall" fn(this: *const RttiSystem, async_id: u32) -> *mut Type,
    get_class: unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Class,
    get_enum: unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Enum,
    get_bitfield:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Bitfield,
    _sub_28: unsafe extern "fastcall" fn(this: *const RttiSystem),
    get_function:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Function,
    _sub_38: unsafe extern "fastcall" fn(this: *const RttiSystem),
    get_native_types:
        unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Type>),
    get_global_functions:
        unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Function>),
    _sub_50: unsafe extern "fastcall" fn(this: *const RttiSystem),
    get_class_functions:
        unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Function>),
    get_enums: unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Enum>),
    get_bitfields: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        out: *mut RedArray<*mut Bitfield>,
        scripted_only: bool,
    ),
    get_classes: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        base_class: *const Class,
        out: *mut RedArray<*mut Class>,
        filter: Option<unsafe extern "C" fn(*const Class) -> bool>,
        include_abstract: bool,
    ),
    get_derived_classes: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        base_class: *const Class,
        out: *mut RedArray<*mut Class>,
    ),
    register_type: unsafe extern "fastcall" fn(this: *mut RttiSystem, ty: *mut Type, async_id: u32),
    _sub_88: unsafe extern "fastcall" fn(this: *const RttiSystem),
    _sub_90: unsafe extern "fastcall" fn(this: *const RttiSystem),
    unregister_type: unsafe extern "fastcall" fn(this: *mut RttiSystem, ty: *mut Type),
    register_function:
        unsafe extern "fastcall" fn(this: *const RttiSystemMut, function: *const GlobalFunction),
    unregister_function:
        unsafe extern "fastcall" fn(this: *const RttiSystem, function: *const GlobalFunction),
    _sub_b0: unsafe extern "fastcall" fn(this: *const RttiSystem),
    _sub_b8: unsafe extern "fastcall" fn(this: *const RttiSystem),
    // FIXME: crashes when used, signature is probably wrong
    _add_register_callback: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        function: unsafe extern "C" fn() -> (),
    ),
    // FIXME: crashes when used, signature is probably wrong
    _add_post_register_callback: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        function: unsafe extern "C" fn() -> (),
    ),
    _sub_d0: unsafe extern "fastcall" fn(this: *const RttiSystem),
    _sub_d8: unsafe extern "fastcall" fn(this: *const RttiSystem),
    _create_scripted_class: unsafe extern "fastcall" fn(
        this: *mut RttiSystem,
        name: CName,
        flags: ClassFlags,
        parent: *const Class,
    ),
    // FIXME: signature is wrong, but how to represent name and value of enumerator ?
    // https://github.com/WopsS/RED4ext.SDK/blob/124984353556f7b343041b810040062fbaa96196/include/RED4ext/RTTISystem.hpp#L50
    _create_scripted_enum: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        name: CName,
        size: i8,
        variants: *mut RedArray<u64>,
    ),
    // FIXME: signature is wrong, but how to represent name and bit ?
    // https://github.com/WopsS/RED4ext.SDK/blob/124984353556f7b343041b810040062fbaa96196/include/RED4ext/RTTISystem.hpp#L54
    _create_scripted_bitfield:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName, bits: *mut RedArray<u64>),
    _initialize_script_runtime: unsafe extern "fastcall" fn(this: *const RttiSystem),
    register_script_name: unsafe extern "fastcall" fn(
        this: *const RttiSystem,
        native_name: CName,
        script_name: CName,
    ),
    get_class_by_script_name:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *const Class,
    get_enum_by_script_name:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *const Enum,
    // FIXME: crashes when used, signature is probably wrong
    _convert_native_to_script_name:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: red::CName) -> red::CName,
    // FIXME: crashes when used, signature is probably wrong
    _convert_script_to_native_name:
        unsafe extern "fastcall" fn(this: *const RttiSystem, name: red::CName) -> red::CName,
}

/// A helper struct to set up RTTI registration callbacks.
#[derive(Debug)]
pub struct RttiRegistrator;

impl RttiRegistrator {
    /// Add a new RTTI registration callback.
    pub fn add(
        register: Option<unsafe extern "C" fn()>,
        post_register: Option<unsafe extern "C" fn()>,
    ) {
        unsafe { red::RTTIRegistrator::Add(register, post_register, false) };
    }
}