commonlibsse_ng\skse\interfaces/
papyrus.rs

1// C++ Original code
2// - ref: https://github.com/SARDONYX-forks/CommonLibVR/blob/ng/include/SKSE/Interfaces.h
3// - ref: https://github.com/SARDONYX-forks/CommonLibVR/blob/ng/src/SKSE/Interfaces.cpp
4// SPDX-FileCopyrightText: (C) 2018 Ryan-rsm-McKenzie
5// SPDX-License-Identifier: MIT
6//
7// SPDX-FileCopyrightText: (C) 2025 SARDONYX
8// SPDX-License-Identifier: Apache-2.0 OR MIT
9
10use crate::{re::BSScript, skse::impls::stab::SKSEPapyrusInterface};
11
12type RegFunction1 = fn(vm: *mut BSScript::Internal::VirtualMachine) -> bool;
13// type RegFunction2 = fn(vm: *mut BSScript::IVirtualMachine) -> bool;
14
15#[derive(Debug, Clone)]
16pub struct PapyrusInterface(&'static SKSEPapyrusInterface);
17
18impl PapyrusInterface {
19    pub const VERSION: u32 = 1;
20
21    #[inline]
22    pub(crate) const fn new(interface: &'static SKSEPapyrusInterface) -> Self {
23        Self(interface)
24    }
25
26    #[inline]
27    pub const fn version(&self) -> u32 {
28        self.0.interfaceVersion
29    }
30
31    #[inline]
32    pub fn register(&self, func: RegFunction1) -> bool {
33        self.register_impl(func)
34    }
35
36    pub fn register_multiple<R>(&self, func_iter: R) -> bool
37    where
38        R: IntoIterator<Item = RegFunction1>,
39    {
40        func_iter.into_iter().all(|f| self.register_impl(f))
41    }
42
43    pub fn register_impl(&self, mut func: RegFunction1) -> bool {
44        let vm = BSScript::Internal::VirtualMachine::get_singleton();
45
46        if !vm.is_null() {
47            func(vm);
48            return true;
49        }
50
51        let result = unsafe { (self.0.Register)((&mut func as *mut RegFunction1).cast()) };
52        if !result {
53            #[cfg(feature = "tracing")]
54            tracing::error!("Failed to register papyrus callback");
55        };
56        result
57    }
58
59    // pub fn register_impl2(&self, mut func: RegFunction2) -> bool {
60    //     let vm = BSScript::Internal::VirtualMachine::get_singleton();
61
62    //     if !vm.is_null() {
63    //         func(vm);
64    //         return true;
65    //     }
66
67    //     let result =
68    //         unsafe { ((*self.get_proxy()).register)((&mut func as *mut RegFunction2).cast()) };
69    //     if !result {
70    //         tracing::error!("Failed to register papyrus callback");
71    //     };
72    //     result
73    // }
74}