├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── .gitmodules ├── .rustfmt.toml ├── Cargo.toml ├── LICENSE ├── README.md ├── build.rs ├── deps └── wrapper.hpp └── src ├── class.rs ├── export.rs ├── invocable.rs ├── lib.rs ├── raw.rs ├── repr.rs ├── systems.rs ├── systems └── rtti.rs ├── types.rs └── types ├── allocator.rs ├── array.rs ├── bytecode.rs ├── cname.rs ├── cruid.rs ├── engine_time.rs ├── entity_id.rs ├── game_engine.rs ├── game_time.rs ├── hash.rs ├── item_id.rs ├── misc.rs ├── opt.rs ├── refs.rs ├── res.rs ├── rtti.rs ├── stack.rs ├── string.rs ├── sync.rs └── tweak_db_id.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "cargo" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: ["master"] 6 | pull_request: 7 | 8 | env: 9 | CARGO_TERM_COLOR: always 10 | 11 | jobs: 12 | check-format: 13 | name: Check formatting 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - run: rustup toolchain install nightly --profile minimal --component rustfmt --no-self-update 18 | - run: cargo +nightly fmt --all -- --check 19 | 20 | lint: 21 | name: Lint 22 | runs-on: windows-2019 23 | steps: 24 | - uses: actions/checkout@v4 25 | with: 26 | submodules: true 27 | - run: rustup toolchain install stable --profile minimal --component clippy --no-self-update 28 | - uses: Swatinem/rust-cache@v2 29 | - run: cargo clippy --all-features -- -D warnings 30 | 31 | test: 32 | name: Test 33 | runs-on: windows-2019 34 | steps: 35 | - uses: actions/checkout@v4 36 | with: 37 | submodules: true 38 | - run: rustup toolchain install stable --profile minimal --no-self-update 39 | - uses: Swatinem/rust-cache@v2 40 | - run: cargo test --all-features 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /.vscode 3 | /Cargo.lock 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "deps/RED4ext.SDK"] 2 | path = deps/RED4ext.SDK 3 | url = https://github.com/WopsS/RED4ext.SDK 4 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 100 2 | unstable_features = true 3 | use_field_init_shorthand = true 4 | imports_granularity = "Module" 5 | reorder_imports = true 6 | group_imports = "StdExternalCrate" 7 | reorder_impl_items = true 8 | reorder_modules = true 9 | format_code_in_doc_comments = true 10 | edition = "2021" 11 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "red4ext-rs" 3 | version = "0.10.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | chrono = { version = "0.4", optional = true } 8 | chrono-tz = { version = "0.10", optional = true } 9 | time = { version = "0.3", optional = true } 10 | thiserror = "2" 11 | sealed = "0.6" 12 | once_cell = "1" 13 | widestring = "1" 14 | const-crc32 = "1" 15 | const-combine = { git = "https://github.com/jac3km4/const-combine", rev = "v0.1.4" } 16 | log = { version = "0.4", optional = true } 17 | 18 | [build-dependencies] 19 | bindgen = { version = "0.72", features = ["experimental"] } 20 | cmake = "0.1" 21 | 22 | [features] 23 | default = [] 24 | chrono = ["dep:chrono", "dep:chrono-tz"] 25 | time = ["dep:time"] 26 | log = ["dep:log"] 27 | 28 | [lints.rust] 29 | warnings = "warn" 30 | future-incompatible = "warn" 31 | let-underscore = "warn" 32 | nonstandard-style = "warn" 33 | rust-2018-compatibility = "warn" 34 | rust-2018-idioms = "warn" 35 | rust-2021-compatibility = "warn" 36 | 37 | [lints.clippy] 38 | all = { level = "warn", priority = -1 } 39 | match_same_arms = "warn" 40 | single_match_else = "warn" 41 | redundant_closure_for_method_calls = "warn" 42 | cloned_instead_of_copied = "warn" 43 | redundant_else = "warn" 44 | unnested_or_patterns = "warn" 45 | type_repetition_in_bounds = "warn" 46 | equatable_if_let = "warn" 47 | implicit_clone = "warn" 48 | explicit_deref_methods = "warn" 49 | explicit_iter_loop = "warn" 50 | inefficient_to_string = "warn" 51 | match_bool = "warn" 52 | 53 | [package.metadata.release] 54 | pre-release-commit-message = "chore: bump version" 55 | publish = false 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 jekky 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # red4ext-rs 2 | 3 | Rust wrapper around [RED4ext.SDK](https://github.com/WopsS/RED4ext.SDK). 4 | 5 | ## documentation 6 | 7 | Read the [documentation](https://jac3km4.github.io/red4ext-rs/red4ext_rs/index.html)! 8 | 9 | ## usage 10 | 11 | ### quickstart 12 | 13 | Define your `Cargo.toml`: 14 | 15 | ```toml 16 | [package] 17 | name = "my-project" 18 | version = "0.1.0" 19 | edition = "2021" 20 | 21 | [lib] 22 | # we want to compile to a DLL 23 | crate-type = ["cdylib"] 24 | 25 | [dependencies] 26 | red4ext-rs = { git = "https://github.com/jac3km4/red4ext-rs", features = ["log"], rev = "v0.10.0" } 27 | # you can also add the bindings crate which exposes all in-game types for convenience 28 | red4ext-rs-bindings = { git = "https://github.com/jac3km4/red4ext-rs-bindings", rev = "v0.6.0" } 29 | ``` 30 | 31 | ### set up a basic plugin 32 | 33 | ```rs 34 | use red4ext_rs::{ 35 | export_plugin_symbols, exports, global, wcstr, Exportable, GlobalExport, Plugin, SemVer, 36 | U16CStr, 37 | }; 38 | 39 | pub struct Example; 40 | 41 | impl Plugin for Example { 42 | const AUTHOR: &'static U16CStr = wcstr!("me"); 43 | const NAME: &'static U16CStr = wcstr!("example"); 44 | const VERSION: SemVer = SemVer::new(0, 1, 0); 45 | 46 | // exports a named global function 47 | fn exports() -> impl Exportable { 48 | exports![ 49 | GlobalExport(global!(c"Add2", add2)), 50 | // you can export global functions and classes 51 | // ClassExport::::builder() 52 | // .base("IScriptable") 53 | // .methods(methods![ 54 | // c"GetValue" => MyClass::value, 55 | // c"SetValue" => MyClass::set_value, 56 | // ]) 57 | // .build() 58 | ] 59 | } 60 | } 61 | 62 | export_plugin_symbols!(Example); 63 | 64 | fn add2(a: i32) -> i32 { 65 | a + 2 66 | } 67 | ``` 68 | 69 | You can now build your project with `cargo build` and copy the compiled DLL from `{project}\target\debug\{project}.dll` to `{game}\red4ext\plugins\`. It should then be loaded by RED4ext and your function should be callable from REDscript and CET. 70 | 71 | ### call global and instance functions 72 | 73 | ```rust 74 | use red4ext_rs::call; 75 | use red4ext_rs::types::{IScriptable, Ref}; 76 | 77 | // you can expose Rust functions to the game as long as their signatures consist of supported 78 | // types, you'll see a compiler error when you try to use an unsupported type like i128 79 | fn example(player: Ref) -> i32 { 80 | // the line below will attempt to look up a matching method in the instance and call it 81 | let size = call!(player, "GetDeviceActionMaxQueueSize;" () -> i32).unwrap(); 82 | // the lines below will attempt to look up a matching static method (scripted or native) and call it 83 | let _ = call!("MathHelper"::"EulerNumber;"() -> f32).unwrap(); 84 | let _ = call!("PlayerPuppet"::"GetCriticalHealthThreshold;" () -> f32).unwrap(); 85 | // the line below invokes a global native function (the operator for adding two Int32) 86 | let added1 = call!("OperatorAdd;Int32Int32;Int32" (size, 4i32) -> i32).unwrap(); 87 | added1 88 | } 89 | ``` 90 | 91 | ### interact with in-game scripted and native types using auto-generated bindings 92 | 93 | See [red4ext-rs-bindings](https://github.com/jac3km4/red4ext-rs-bindings) for bindings for all 94 | types defined in RTTI in the game. 95 | 96 | ### define and export your own class type 97 | 98 | ```rust 99 | use std::cell::Cell; 100 | 101 | use red4ext_rs::types::IScriptable; 102 | use red4ext_rs::{class_kind, exports, methods, ClassExport, Exportable, ScriptClass}; 103 | 104 | // ...defined in impl Plugin 105 | fn exports() -> impl Exportable { 106 | exports![ClassExport::::builder() 107 | .base("IScriptable") 108 | .methods(methods![ 109 | c"GetValue" => MyClass::value, 110 | c"SetValue" => MyClass::set_value, 111 | event c"OnInitialize" => MyClass::on_initialize 112 | ]) 113 | .build(),] 114 | } 115 | 116 | #[derive(Debug, Default, Clone)] 117 | #[repr(C)] 118 | struct MyClass { 119 | base: IScriptable, 120 | value: Cell, 121 | } 122 | 123 | impl MyClass { 124 | fn value(&self) -> i32 { 125 | self.value.get() 126 | } 127 | 128 | fn set_value(&self, value: i32) { 129 | self.value.set(value); 130 | } 131 | 132 | fn on_initialize(&self) {} 133 | } 134 | 135 | unsafe impl ScriptClass for MyClass { 136 | type Kind = class_kind::Native; 137 | 138 | const NAME: &'static str = "MyClass"; 139 | } 140 | ``` 141 | 142 | ...and on REDscript side: 143 | 144 | ```swift 145 | native class MyClass { 146 | native func GetValue() -> Int32; 147 | native func SetValue(a: Int32); 148 | native cb func OnInitialize(); 149 | } 150 | ``` 151 | 152 | ### interact with scripted classes using hand-written bindings 153 | 154 | ```rust 155 | use red4ext_rs::types::{EntityId, Ref}; 156 | use red4ext_rs::{class_kind, ScriptClass, ScriptClassOps}; 157 | 158 | #[repr(C)] 159 | struct AddInvestigatorEvent { 160 | investigator: EntityId, 161 | } 162 | 163 | unsafe impl ScriptClass for AddInvestigatorEvent { 164 | type Kind = class_kind::Scripted; 165 | 166 | const NAME: &'static str = "AddInvestigatorEvent"; 167 | } 168 | 169 | fn example() -> Ref { 170 | // we can create new refs of script classes 171 | let instance = AddInvestigatorEvent::new_ref_with(|inst| { 172 | inst.investigator = EntityId::from(0xdeadbeef); 173 | }) 174 | .unwrap(); 175 | 176 | // we can obtain a reference to the fields of the ref 177 | let fields = unsafe { instance.fields() }.unwrap(); 178 | let _investigator = fields.investigator; 179 | 180 | instance 181 | } 182 | ``` 183 | 184 | ### interact with native classes using hand-written bindings 185 | 186 | ```rust 187 | use red4ext_rs::types::{IScriptable, Ref}; 188 | use red4ext_rs::{class_kind, ScriptClass, ScriptClassOps}; 189 | 190 | #[repr(C)] 191 | struct ScanningEvent { 192 | base: IScriptable, 193 | state: u8, 194 | } 195 | 196 | unsafe impl ScriptClass for ScanningEvent { 197 | type Kind = class_kind::Native; 198 | 199 | const NAME: &'static str = "gameScanningEvent"; 200 | } 201 | 202 | fn example() -> Ref { 203 | ScanningEvent::new_ref_with(|inst| { 204 | inst.state = 1; 205 | }) 206 | .unwrap() 207 | } 208 | ``` 209 | 210 | ### interact with native game systems 211 | 212 | ```rust 213 | use red4ext_rs::types::{CName, EntityId, GameEngine, Opt}; 214 | use red4ext_rs::{call, RttiSystem}; 215 | 216 | fn example() { 217 | let rtti = RttiSystem::get(); 218 | let class = rtti.get_class(CName::new("gameGameAudioSystem")).unwrap(); 219 | let engine = GameEngine::get(); 220 | let game = engine.game_instance(); 221 | let system = game.get_system(class.as_type()); 222 | call!(system, "Play" (CName::new("ono_v_pain_long"), Opt::::Default, Opt::::Default) -> ()).unwrap() 223 | } 224 | ``` 225 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::path::{Path, PathBuf}; 3 | 4 | fn main() { 5 | let red4ext_dir = Path::new("deps/RED4ext.SDK"); 6 | let red4ext_include_dir = red4ext_dir.join("include"); 7 | 8 | let red4ext_target = cmake::Config::new(red4ext_dir).profile("Release").build(); 9 | 10 | println!( 11 | "cargo:rustc-link-search=native={}", 12 | red4ext_target.join("lib").display() 13 | ); 14 | println!("cargo:rustc-link-lib=user32"); 15 | println!("cargo:rustc-link-lib=RED4ext.SDK"); 16 | 17 | let bindings = bindgen::Builder::default() 18 | .clang_arg("-std=c++20") 19 | .clang_arg(format!("-I{}", red4ext_include_dir.display())) 20 | .header("deps/wrapper.hpp") 21 | .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) 22 | .default_enum_style(bindgen::EnumVariation::ModuleConsts) 23 | .derive_default(true) 24 | .enable_cxx_namespaces() 25 | .wrap_static_fns(true) 26 | .vtable_generation(true) 27 | // std types get generated incorrectly for some reason, so they need to be opaque 28 | .opaque_type("std::(vector|string|filesystem).*") 29 | .allowlist_item("RED4ext::[^:]+") 30 | .allowlist_item("RED4ext::(Detail|ent)::.+") 31 | .allowlist_item("RED4ext::Memory::(Vault|IAllocator)") 32 | .allowlist_item("versioning::.+") 33 | // callback handlers generate incorrect Rust code 34 | .blocklist_item("RED4ext::(Detail::)?CallbackHandler.*") 35 | .generate_comments(false) 36 | .generate() 37 | .expect("Unable to generate bindings"); 38 | 39 | let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); 40 | bindings 41 | .write_to_file(out_path.join("bindings.rs")) 42 | .expect("Couldn't write bindings!"); 43 | #[cfg(debug_assertions)] 44 | println!( 45 | "cargo:warning=Generated bindings: {}", 46 | out_path.join("bindings.rs").display() 47 | ); 48 | } 49 | -------------------------------------------------------------------------------- /deps/wrapper.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace versioning 10 | { 11 | static constexpr uint16_t RUNTIME_INDEPENDENT = -1; 12 | static constexpr uint8_t SDK_MAJOR = RED4EXT_VER_MAJOR; 13 | static constexpr uint16_t SDK_MINOR = RED4EXT_VER_MINOR; 14 | static constexpr uint32_t SDK_PATCH = RED4EXT_VER_PATCH; 15 | static constexpr uint32_t API_VERSION_LATEST = RED4EXT_API_VERSION_LATEST; 16 | } 17 | -------------------------------------------------------------------------------- /src/class.rs: -------------------------------------------------------------------------------- 1 | use sealed::sealed; 2 | 3 | use crate::types::{IScriptable, Ref}; 4 | 5 | /// A trait for types that represent script classes. 6 | /// 7 | /// # Safety 8 | /// Implementors must ensure that the type's layout is compatible with the layout of the native 9 | /// type that has the specified name. 10 | pub unsafe trait ScriptClass: Sized { 11 | type Kind: ClassKind; 12 | 13 | const NAME: &'static str; 14 | } 15 | 16 | /// A trait for distinguishing between native and scripted classes. 17 | #[sealed] 18 | pub trait ClassKind { 19 | type NativeType; 20 | 21 | fn fields(inst: &Self::NativeType) -> &T; 22 | fn fields_mut(inst: &mut Self::NativeType) -> &mut T; 23 | } 24 | 25 | /// Marker types for distinguishing between native and scripted classes. 26 | pub mod class_kind { 27 | use super::*; 28 | 29 | /// A marker type for scripted classes. Scripted classes are stored with an additional level of 30 | /// indirection inside of [`IScriptable`]. 31 | #[derive(Debug)] 32 | pub struct Scripted; 33 | 34 | #[sealed] 35 | impl ClassKind for Scripted { 36 | type NativeType = IScriptable; 37 | 38 | #[inline] 39 | fn fields(inst: &Self::NativeType) -> &T { 40 | unsafe { &*inst.fields().as_ptr().cast::() } 41 | } 42 | 43 | #[inline] 44 | fn fields_mut(inst: &mut Self::NativeType) -> &mut T { 45 | unsafe { &mut *inst.fields().as_ptr().cast::() } 46 | } 47 | } 48 | 49 | /// A marker type for native classes. Native classes are represented directly by their native type. 50 | #[derive(Debug)] 51 | pub struct Native; 52 | 53 | #[sealed] 54 | impl ClassKind for Native { 55 | type NativeType = T; 56 | 57 | #[inline] 58 | fn fields(inst: &Self::NativeType) -> &T { 59 | inst 60 | } 61 | 62 | #[inline] 63 | fn fields_mut(inst: &mut Self::NativeType) -> &mut T { 64 | inst 65 | } 66 | } 67 | } 68 | 69 | /// A trait for operations on script classes. 70 | #[sealed] 71 | pub trait ScriptClassOps: ScriptClass { 72 | /// Creates a new reference to the class. 73 | fn new_ref() -> Option>; 74 | /// Creates a new reference to the class and initializes it with the provided function. 75 | fn new_ref_with(init: impl FnOnce(&mut Self)) -> Option>; 76 | } 77 | 78 | #[sealed] 79 | impl ScriptClassOps for T { 80 | #[inline] 81 | fn new_ref() -> Option> { 82 | Ref::new() 83 | } 84 | 85 | #[inline] 86 | fn new_ref_with(init: impl FnOnce(&mut Self)) -> Option> { 87 | Ref::new_with(init) 88 | } 89 | } 90 | 91 | pub type NativeType = <::Kind as ClassKind>::NativeType; 92 | -------------------------------------------------------------------------------- /src/export.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CString; 2 | use std::marker::PhantomData; 3 | 4 | use sealed::sealed; 5 | 6 | use crate::invocable::{GlobalMetadata, MethodMetadata}; 7 | use crate::systems::RttiSystemMut; 8 | use crate::types::{CName, NativeClass}; 9 | use crate::{NativeRepr, RttiSystem, ScriptClass, class_kind}; 10 | 11 | /// A list of exports to register with the game. 12 | #[derive(Debug)] 13 | pub struct ExportList { 14 | head: H, 15 | tail: T, 16 | } 17 | 18 | impl ExportList { 19 | /// Create a new `ExportList` with the given head and tail. 20 | pub const fn new(head: H, tail: T) -> Self { 21 | Self { head, tail } 22 | } 23 | } 24 | 25 | /// A trait for types to be exported to the game. 26 | #[sealed] 27 | pub trait Exportable { 28 | fn register(&self); 29 | fn post_register(&self); 30 | } 31 | 32 | #[sealed] 33 | impl Exportable for ExportList 34 | where 35 | H: Exportable, 36 | T: Exportable, 37 | { 38 | #[inline] 39 | fn register(&self) { 40 | self.head.register(); 41 | self.tail.register(); 42 | } 43 | 44 | #[inline] 45 | fn post_register(&self) { 46 | self.head.post_register(); 47 | self.tail.post_register(); 48 | } 49 | } 50 | 51 | /// A type representing an empty list of exports. 52 | #[derive(Debug)] 53 | pub struct ExportNil; 54 | 55 | #[sealed] 56 | impl Exportable for ExportNil { 57 | #[inline] 58 | fn register(&self) {} 59 | 60 | #[inline] 61 | fn post_register(&self) {} 62 | } 63 | 64 | /// A single class export. 65 | /// This can be used to define a custom class to be exported to the game. 66 | /// This type should not be used for structs, use [`StructExport`] instead. 67 | #[derive(Debug)] 68 | pub struct ClassExport { 69 | base: &'static str, 70 | methods: &'static [MethodMetadata], 71 | static_methods: &'static [GlobalMetadata], 72 | } 73 | 74 | impl ClassExport { 75 | pub fn builder() -> ClassExportBuilder { 76 | ClassExportBuilder { 77 | base: "IScriptable", 78 | methods: &[], 79 | static_methods: &[], 80 | } 81 | } 82 | } 83 | 84 | #[sealed] 85 | impl> Exportable for ClassExport { 86 | fn register(&self) { 87 | let mut rtti = RttiSystemMut::get(); 88 | let name_cstr = CString::new(C::NAME).expect("name should be valid"); 89 | let base = rtti 90 | .get_class(CName::new(self.base)) 91 | .expect("base should exist"); 92 | let handle = NativeClass::::new_handle(&name_cstr, Some(base)); 93 | rtti.register_class(handle); 94 | } 95 | 96 | fn post_register(&self) { 97 | let (converted_methods, converted_static_methods) = { 98 | let rtti_ro = RttiSystem::get(); 99 | let class = rtti_ro 100 | .get_class(CName::new(C::NAME)) 101 | .expect("class should exist"); 102 | let converted_methods = self 103 | .methods 104 | .iter() 105 | .map(|m| m.to_rtti(class)) 106 | .collect::>(); 107 | let converted_static_methods = self 108 | .static_methods 109 | .iter() 110 | .map(|m| m.to_rtti_static_method(class)) 111 | .collect::>(); 112 | (converted_methods, converted_static_methods) 113 | }; 114 | 115 | let mut rtti_rw = RttiSystemMut::get(); 116 | let class = rtti_rw 117 | .get_class(CName::new(C::NAME)) 118 | .expect("class should exist"); 119 | 120 | for method in converted_methods { 121 | class.add_method(method); 122 | } 123 | for static_method in converted_static_methods { 124 | class.add_static_method(static_method); 125 | } 126 | } 127 | } 128 | 129 | /// A builder for [`ClassExport`]. 130 | #[derive(Debug)] 131 | pub struct ClassExportBuilder { 132 | base: &'static str, 133 | methods: &'static [MethodMetadata], 134 | static_methods: &'static [GlobalMetadata], 135 | } 136 | 137 | impl ClassExportBuilder { 138 | /// Set the base class of the class to be exported. 139 | /// This is set to `IScriptable` by default. 140 | pub const fn base(mut self, base: &'static str) -> Self { 141 | self.base = base; 142 | self 143 | } 144 | 145 | /// Set the methods of the class to be exported. 146 | /// See the [`methods!`](crate::methods) macro for a convenient way to define methods. 147 | pub const fn methods(mut self, methods: &'static [MethodMetadata]) -> Self { 148 | self.methods = methods; 149 | self 150 | } 151 | 152 | /// Set the static methods of the class to be exported. 153 | /// See the [`static_methods!`](crate::static_methods) macro for a convenient way to define methods. 154 | pub const fn static_methods(mut self, static_methods: &'static [GlobalMetadata]) -> Self { 155 | self.static_methods = static_methods; 156 | self 157 | } 158 | 159 | /// Build the final [`ClassExport`] instance. 160 | pub const fn build(self) -> ClassExport { 161 | ClassExport { 162 | base: self.base, 163 | methods: self.methods, 164 | static_methods: self.static_methods, 165 | } 166 | } 167 | } 168 | 169 | /// A single struct export. 170 | /// This can be used to define a custom struct to be exported to the game. 171 | #[derive(Debug)] 172 | pub struct StructExport { 173 | base: Option<&'static str>, 174 | static_methods: &'static [GlobalMetadata], 175 | _phantom: PhantomData C>, 176 | } 177 | 178 | impl StructExport { 179 | pub fn builder() -> StructExportBuilder { 180 | StructExportBuilder { 181 | base: None, 182 | static_methods: &[], 183 | _phantom: PhantomData, 184 | } 185 | } 186 | } 187 | 188 | #[sealed] 189 | impl Exportable for StructExport { 190 | fn register(&self) { 191 | let mut rtti = RttiSystemMut::get(); 192 | let name_cstr = CString::new(C::NAME).expect("name should be valid"); 193 | let base = self 194 | .base 195 | .map(|base| &*rtti.get_class(CName::new(base)).expect("base should exist")); 196 | let handle = NativeClass::::new_handle(&name_cstr, base); 197 | rtti.register_class(handle); 198 | } 199 | 200 | fn post_register(&self) { 201 | let converted_static_methods = { 202 | let rtti_ro = RttiSystem::get(); 203 | let class = rtti_ro 204 | .get_class(CName::new(C::NAME)) 205 | .expect("class should exist"); 206 | self.static_methods 207 | .iter() 208 | .map(|m| m.to_rtti_static_method(class)) 209 | .collect::>() 210 | }; 211 | 212 | let mut rtti_rw = RttiSystemMut::get(); 213 | let class = rtti_rw 214 | .get_class(CName::new(C::NAME)) 215 | .expect("class should exist"); 216 | 217 | for static_method in converted_static_methods { 218 | class.add_static_method(static_method); 219 | } 220 | } 221 | } 222 | 223 | /// A builder for [`StructExport`]. 224 | #[derive(Debug)] 225 | pub struct StructExportBuilder { 226 | base: Option<&'static str>, 227 | static_methods: &'static [GlobalMetadata], 228 | _phantom: PhantomData C>, 229 | } 230 | 231 | impl StructExportBuilder { 232 | /// Set the base type of the struct to be exported. 233 | /// Structs do not have a base type by default. 234 | pub const fn base(mut self, base: &'static str) -> Self { 235 | self.base = Some(base); 236 | self 237 | } 238 | 239 | /// Set the static methods of the struct to be exported. 240 | /// See the [`static_methods!`](crate::static_methods) macro for a convenient way to define methods. 241 | pub const fn static_methods(mut self, static_methods: &'static [GlobalMetadata]) -> Self { 242 | self.static_methods = static_methods; 243 | self 244 | } 245 | 246 | /// Build the final [`StructExport`] instance. 247 | pub const fn build(self) -> StructExport { 248 | StructExport { 249 | base: self.base, 250 | static_methods: self.static_methods, 251 | _phantom: PhantomData, 252 | } 253 | } 254 | } 255 | 256 | /// A single global function export. 257 | #[derive(Debug)] 258 | pub struct GlobalExport(pub GlobalMetadata); 259 | 260 | #[sealed] 261 | impl Exportable for GlobalExport { 262 | #[inline] 263 | fn register(&self) {} 264 | 265 | fn post_register(&self) { 266 | let converted = self.0.to_rtti(); 267 | 268 | let mut rtti = RttiSystemMut::get(); 269 | rtti.register_function(converted); 270 | } 271 | } 272 | 273 | /// Creates a list of exports to be registered within the game's RTTI system. 274 | /// 275 | /// # Example 276 | /// ```rust 277 | /// use std::cell::Cell; 278 | /// 279 | /// use red4ext_rs::{ClassExport, Exportable, GlobalExport, ScriptClass, class_kind, exports, methods, global}; 280 | /// use red4ext_rs::types::IScriptable; 281 | /// 282 | /// fn exports() -> impl Exportable { 283 | /// exports![ 284 | /// GlobalExport(global!(c"GlobalExample", global_example)), 285 | /// ClassExport::::builder() 286 | /// .base("IScriptable") 287 | /// .methods(methods![ 288 | /// c"Value" => MyClass::value, 289 | /// c"SetValue" => MyClass::set_value, 290 | /// ]) 291 | /// .build(), 292 | /// ] 293 | /// } 294 | /// 295 | /// fn global_example() -> String { 296 | /// "Hello, world!".to_string() 297 | /// } 298 | /// 299 | /// #[derive(Debug, Default, Clone)] 300 | /// #[repr(C)] 301 | /// struct MyClass { 302 | /// // You must include the base native class in your Rust struct. 303 | /// base: IScriptable, 304 | /// value: Cell, 305 | /// } 306 | /// 307 | /// impl MyClass { 308 | /// fn value(&self) -> i32 { 309 | /// self.value.get() 310 | /// } 311 | /// 312 | /// fn set_value(&self, value: i32) { 313 | /// self.value.set(value) 314 | /// } 315 | /// } 316 | /// 317 | /// unsafe impl ScriptClass for MyClass { 318 | /// const NAME: &'static str = "MyClass"; 319 | /// type Kind = class_kind::Native; 320 | /// } 321 | #[macro_export] 322 | macro_rules! exports { 323 | [$export:expr, $($tt:tt)*] => { 324 | $crate::ExportList::new($export, exports!($($tt)*)) 325 | }; 326 | [$export:expr] => { 327 | $crate::ExportList::new($export, $crate::ExportNil) 328 | }; 329 | [] => { $crate::ExportNil } 330 | } 331 | 332 | /// Define a list of methods to register with the game. Usually used in conjuction with 333 | /// [`exports!`]. 334 | #[macro_export] 335 | macro_rules! methods { 336 | [$( $($mod:ident)* $name:literal => $ty:ident::$id:ident),*$(,)?] => { 337 | const { &[$($crate::method!($($mod)* $name, $ty::$id)),*] } 338 | }; 339 | } 340 | 341 | /// Define a list of static methods to register with the game. Usually used in conjuction with 342 | /// [`exports!`]. 343 | #[macro_export] 344 | macro_rules! static_methods { 345 | [$( $($mod:ident)* $name:literal => $ty:ident::$id:ident),*$(,)?] => { 346 | const { &[$($crate::global!($($mod)* $name, $ty::$id)),*] } 347 | }; 348 | } 349 | -------------------------------------------------------------------------------- /src/invocable.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::CStr; 2 | use std::marker::PhantomData; 3 | use std::mem::MaybeUninit; 4 | 5 | use sealed::sealed; 6 | use thiserror::Error; 7 | 8 | use crate::class::ClassKind; 9 | use crate::repr::{FromRepr, IntoRepr, NativeRepr}; 10 | use crate::types::{ 11 | CName, Class, Function, FunctionFlags, FunctionHandler, GlobalFunction, IScriptable, Method, 12 | PoolRef, Ref, StackArg, StackFrame, StaticMethod, 13 | }; 14 | use crate::{ScriptClass, VoidPtr}; 15 | 16 | /// An error returned when invoking a function fails. 17 | #[derive(Debug, Error)] 18 | pub enum InvokeError { 19 | #[error("function could not be found by full name '{0}'")] 20 | FunctionNotFound(&'static str), 21 | #[error("class could not be found by name '{0}'")] 22 | ClassNotFound(&'static str), 23 | #[error( 24 | "method could not be found by full name '{0}', available options: {options}", 25 | options = .1.iter() 26 | .fold(String::new() ,|mut acc, el| { 27 | if !acc.is_empty() { 28 | acc.push_str(", "); 29 | } 30 | acc.push('\''); 31 | acc.push_str(el.as_str()); 32 | acc.push('\''); 33 | acc 34 | }) 35 | )] 36 | MethodNotFound(&'static str, Box<[CName]>), 37 | #[error("invalid number of arguments, expected {expected} for {function}")] 38 | InvalidArgCount { 39 | function: &'static str, 40 | expected: u32, 41 | }, 42 | #[error("expected '{expected}' argument type at index {index} for '{function}'")] 43 | ArgMismatch { 44 | function: &'static str, 45 | expected: &'static str, 46 | index: usize, 47 | }, 48 | #[error("return type mismatch, expected '{expected}' for '{function}'")] 49 | ReturnMismatch { 50 | function: &'static str, 51 | expected: &'static str, 52 | }, 53 | #[error("could not resolve type {0}")] 54 | UnresolvedType(&'static str), 55 | #[error("execution of '{0}' has failed")] 56 | ExecutionFailed(&'static str), 57 | #[error("the 'this' pointer for class '{0}' was null")] 58 | NullReceiver(&'static str), 59 | } 60 | 61 | impl InvokeError { 62 | #[doc(hidden)] 63 | #[cold] 64 | pub fn new_method_not_found<'a>( 65 | name: &'static str, 66 | options: impl IntoIterator, 67 | ) -> InvokeError { 68 | let options = options 69 | .into_iter() 70 | .map(|m| m.as_function().name()) 71 | .collect(); 72 | InvokeError::MethodNotFound(name, options) 73 | } 74 | } 75 | 76 | /// A trait for functions that can be exported as global functions. 77 | #[sealed] 78 | pub trait GlobalInvocable { 79 | const FN_TYPE: FunctionType; 80 | 81 | fn invoke(self, ctx: &IScriptable, frame: &mut StackFrame, ret: Option<&mut MaybeUninit>); 82 | } 83 | 84 | macro_rules! impl_global_invocable { 85 | ($( ($( $types:ident ),*) ),*) => { 86 | $( 87 | #[allow(non_snake_case, unused_variables)] 88 | #[sealed] 89 | impl<$($types,)* R, FN> GlobalInvocable<($($types,)*), R::Repr> for FN 90 | where 91 | FN: Fn($($types,)*) -> R, 92 | $($types: FromRepr, $types::Repr: Default,)* 93 | R: IntoRepr 94 | { 95 | const FN_TYPE: FunctionType = FunctionType { 96 | args: &[$(CName::new($types::Repr::NAME),)*], 97 | ret: CName::new(R::Repr::NAME) 98 | }; 99 | 100 | #[inline] 101 | fn invoke(self, _ctx: &IScriptable, frame: &mut StackFrame, ret: Option<&mut MaybeUninit>) { 102 | $(let $types = unsafe { frame.get_arg::<$types>() };)* 103 | let res = self($($types,)*); 104 | if let Some(ret) = ret { 105 | unsafe { ret.as_mut_ptr().write(res.into_repr()) }; 106 | } 107 | } 108 | } 109 | )* 110 | }; 111 | } 112 | 113 | impl_global_invocable!( 114 | (), 115 | (A), 116 | (A, B), 117 | (A, B, C), 118 | (A, B, C, D), 119 | (A, B, C, D, E), 120 | (A, B, C, D, E, F), 121 | (A, B, C, D, E, F, G) 122 | ); 123 | 124 | /// A trait for functions that can be exported as class methods. 125 | #[sealed] 126 | pub trait MethodInvocable { 127 | const FN_TYPE: FunctionType; 128 | 129 | fn invoke(self, ctx: &Ctx, frame: &mut StackFrame, ret: Option<&mut MaybeUninit>); 130 | } 131 | 132 | macro_rules! impl_method_invocable { 133 | ($( ($( $types:ident ),*) ),*) => { 134 | $( 135 | #[allow(non_snake_case, unused_variables)] 136 | #[sealed] 137 | impl MethodInvocable for FN 138 | where 139 | FN: Fn(&Ctx, $($types,)*) -> R, 140 | $($types: FromRepr, $types::Repr: Default,)* 141 | R: IntoRepr 142 | { 143 | const FN_TYPE: FunctionType = FunctionType { 144 | args: &[$(CName::new($types::Repr::NAME),)*], 145 | ret: CName::new(R::Repr::NAME) 146 | }; 147 | 148 | #[inline] 149 | fn invoke(self, ctx: &Ctx, frame: &mut StackFrame, ret: Option<&mut MaybeUninit>) { 150 | $(let $types = unsafe { frame.get_arg::<$types>() };)* 151 | let res = self(ctx, $($types,)*); 152 | if let Some(ret) = ret { 153 | unsafe { ret.as_mut_ptr().write(res.into_repr()) }; 154 | } 155 | } 156 | } 157 | )* 158 | }; 159 | } 160 | 161 | impl_method_invocable!( 162 | (), 163 | (A), 164 | (A, B), 165 | (A, B, C), 166 | (A, B, C, D), 167 | (A, B, C, D, E), 168 | (A, B, C, D, E, F), 169 | (A, B, C, D, E, F, G) 170 | ); 171 | 172 | /// A representation of a function type, including its arguments and return type. 173 | #[derive(Debug)] 174 | pub struct FunctionType { 175 | args: &'static [CName], 176 | ret: CName, 177 | } 178 | 179 | impl FunctionType { 180 | fn initialize_func(&self, func: &mut Function) { 181 | for &arg in self.args { 182 | func.add_param(arg, c"", false, false); 183 | } 184 | func.set_return_type(self.ret); 185 | } 186 | } 187 | 188 | /// A representation of a global function, including its name, a function handler, and its type. 189 | #[derive(Debug)] 190 | pub struct GlobalMetadata { 191 | name: &'static CStr, 192 | func: FunctionHandler, 193 | typ: FunctionType, 194 | } 195 | 196 | impl GlobalMetadata { 197 | #[doc(hidden)] 198 | #[inline] 199 | pub const fn new, A, R>( 200 | name: &'static CStr, 201 | func: FunctionHandler, 202 | _f: &F, 203 | ) -> Self { 204 | Self { 205 | name, 206 | func, 207 | typ: F::FN_TYPE, 208 | } 209 | } 210 | 211 | /// Converts this metadata into a [`GlobalFunction`] instance, which can be registered with 212 | /// [RttiSystemMut](crate::RttiSystemMut). 213 | pub fn to_rtti(&self) -> PoolRef { 214 | let mut flags = FunctionFlags::default(); 215 | flags.set_is_native(true); 216 | flags.set_is_final(true); 217 | flags.set_is_static(true); 218 | let mut func = GlobalFunction::new(self.name, self.name, self.func, flags); 219 | self.typ.initialize_func(func.as_function_mut()); 220 | func 221 | } 222 | 223 | /// Converts this metadata into a [`StaticMethod`] instance, which can be registered with 224 | /// [RttiSystemMut](crate::RttiSystemMut). 225 | pub fn to_rtti_static_method(&self, class: &Class) -> PoolRef { 226 | let mut flags = FunctionFlags::default(); 227 | flags.set_is_native(true); 228 | flags.set_is_final(true); 229 | flags.set_is_static(true); 230 | 231 | let mut func = StaticMethod::new(self.name, self.name, class, self.func, flags); 232 | self.typ.initialize_func(func.as_function_mut()); 233 | func 234 | } 235 | } 236 | 237 | /// A representation of a class method, including its name, a function handler, and its type. 238 | #[derive(Debug)] 239 | pub struct MethodMetadata { 240 | name: &'static CStr, 241 | func: FunctionHandler, 242 | typ: FunctionType, 243 | parent: PhantomData *const Ctx>, 244 | is_event: bool, 245 | is_final: bool, 246 | } 247 | 248 | impl MethodMetadata { 249 | #[doc(hidden)] 250 | #[inline] 251 | pub const fn new, A, R>( 252 | name: &'static CStr, 253 | ptr: FunctionHandler, 254 | _f: &F, 255 | ) -> Self { 256 | Self { 257 | name, 258 | func: ptr, 259 | typ: F::FN_TYPE, 260 | parent: PhantomData, 261 | is_event: false, 262 | is_final: false, 263 | } 264 | } 265 | 266 | /// Configures this method as an event handler (called `cb` in REDscript). 267 | pub const fn with_is_event(mut self) -> Self { 268 | self.is_event = true; 269 | self 270 | } 271 | 272 | /// Configures this method as final (cannot be overridden). 273 | pub const fn with_is_final(mut self) -> Self { 274 | self.is_final = true; 275 | self 276 | } 277 | 278 | /// Converts this metadata into a [`Method`] instance, which can be registered with 279 | /// the [RttiSystemMut](crate::RttiSystemMut). 280 | pub fn to_rtti(&self, class: &Class) -> PoolRef { 281 | let mut flags = FunctionFlags::default(); 282 | flags.set_is_native(true); 283 | flags.set_is_event(self.is_event); 284 | flags.set_is_final(self.is_final); 285 | 286 | let mut func = Method::new(self.name, self.name, class, self.func, flags); 287 | self.typ.initialize_func(func.as_function_mut()); 288 | func 289 | } 290 | } 291 | 292 | /// A macro for defining global functions. Usually used in conjunction with the 293 | /// [`exports!`](crate::exports) macro. 294 | /// 295 | /// # Example 296 | /// ```rust 297 | /// use red4ext_rs::{GlobalInvocable, GlobalMetadata, global}; 298 | /// 299 | /// fn my_global() -> GlobalMetadata { 300 | /// global!(c"Adder", adder) 301 | /// } 302 | /// 303 | /// fn adder(a: i32, b: i32) -> i32 { 304 | /// a + b 305 | /// } 306 | /// ``` 307 | #[macro_export] 308 | macro_rules! global { 309 | ($name:literal, $fun:expr) => {{ 310 | extern "C" fn native_impl( 311 | ctx: &$crate::types::IScriptable, 312 | frame: &mut $crate::types::StackFrame, 313 | ret: $crate::VoidPtr, 314 | _unk: i64, 315 | ) { 316 | let out = unsafe { std::mem::transmute(ret) }; 317 | $crate::GlobalInvocable::invoke($fun, ctx, frame, out); 318 | unsafe { frame.step() }; 319 | } 320 | 321 | $crate::GlobalMetadata::new($name, native_impl, &$fun) 322 | }}; 323 | } 324 | 325 | /// A macro for defining class methods. Usually used in conjunction with the 326 | /// [`methods!`](crate::methods) macro. 327 | #[macro_export] 328 | macro_rules! method { 329 | ($name:literal, $ty:ident::$id:ident $($mods:ident)*) => {{ 330 | extern "C" fn native_impl( 331 | ctx: &$ty, 332 | frame: &mut $crate::types::StackFrame, 333 | ret: $crate::VoidPtr, 334 | _unk: i64, 335 | ) { 336 | let out = unsafe { ::std::mem::transmute(ret) }; 337 | $crate::MethodInvocable::invoke($ty::$id, ctx, frame, out); 338 | unsafe { frame.step() }; 339 | } 340 | 341 | $crate::MethodMetadata::new($name, native_impl, &$ty::$id) 342 | $(.$mods())? 343 | }}; 344 | (event $name:literal, $ty:ident::$id:ident $($mods:ident)*) => { 345 | $crate::method!($name, $ty::$id with_is_event $($mods)*) 346 | }; 347 | (final $name:literal, $ty:ident::$id:ident $($mods:ident)*) => { 348 | $crate::method!($name, $ty::$id with_is_final $($mods)*) 349 | } 350 | } 351 | 352 | /// A macro for conveniently calling functions and methods. 353 | /// If you're calling a method, the first argument should be the instance of the class. 354 | /// The next argument should be a full function name, which might have to include mangled names of 355 | /// the parameter types. 356 | /// 357 | /// # Example 358 | /// ```rust 359 | /// use red4ext_rs::{call, types::{IScriptable, Ref, CName}}; 360 | /// 361 | /// fn method_example(inst: Ref) -> CName { 362 | /// call!(inst, "GetClassName" () -> CName).unwrap() 363 | /// } 364 | /// 365 | /// fn global_example() -> i32 { 366 | /// call!("OperatorAdd;Int32Int32;Int32" (1i32, 2i32) -> i32).unwrap() 367 | /// } 368 | /// 369 | /// fn static_example() -> f32 { 370 | /// call!("PlayerPuppet"::"GetCriticalHealthThreshold;" () -> f32).unwrap() 371 | /// } 372 | /// ``` 373 | #[macro_export] 374 | macro_rules! call { 375 | ($cls_name:literal :: $fn_name:literal ($( $args:expr ),*) -> $rett:ty) => { 376 | (|| { 377 | let rtti = $crate::RttiSystem::get(); 378 | let ctx = rtti 379 | .resolve_static_context($crate::types::CName::new($cls_name)) 380 | .ok_or($crate::InvokeError::ClassNotFound($cls_name))?; 381 | rtti 382 | .resolve_static_method_by_full_name(::std::concat!($cls_name, "::", $fn_name)) 383 | .ok_or($crate::InvokeError::FunctionNotFound($fn_name))? 384 | .execute::<_, $rett>( 385 | unsafe { ctx.instance() }.map(::std::convert::AsRef::as_ref), 386 | ($( $crate::IntoRepr::into_repr($args), )*) 387 | ) 388 | })() 389 | }; 390 | ($fn_name:literal ($( $args:expr ),*) -> $rett:ty) => { 391 | (|| { 392 | $crate::RttiSystem::get() 393 | .get_function($crate::types::CName::new($fn_name)) 394 | .ok_or($crate::InvokeError::FunctionNotFound($fn_name))? 395 | .execute::<_, $rett>(None, ($( $crate::IntoRepr::into_repr($args), )*)) 396 | })() 397 | }; 398 | ($this:expr, $fn_name:literal ($( $args:expr ),*) -> $rett:ty) => { 399 | (|| { 400 | let receiver = $crate::AsReceiver::as_receiver(&$this)?; 401 | $crate::types::IScriptable::class(receiver) 402 | .get_method($crate::types::CName::new($fn_name)) 403 | .map_err(|err| $crate::InvokeError::new_method_not_found($fn_name, err))? 404 | .as_function() 405 | .execute::<_, $rett>( 406 | Some(receiver), 407 | ($( $crate::IntoRepr::into_repr($args), )*) 408 | ) 409 | })() 410 | }; 411 | } 412 | 413 | /// A trait for types that can be used as the receiver of a method call. 414 | #[sealed] 415 | pub trait AsReceiver { 416 | #[doc(hidden)] 417 | fn as_receiver(&self) -> Result<&IScriptable, InvokeError>; 418 | } 419 | 420 | #[sealed] 421 | impl> AsReceiver for T { 422 | #[inline] 423 | fn as_receiver(&self) -> Result<&IScriptable, InvokeError> { 424 | Ok(self.as_ref()) 425 | } 426 | } 427 | 428 | #[sealed] 429 | impl AsReceiver for Ref 430 | where 431 | >::NativeType: AsRef, 432 | { 433 | #[inline] 434 | fn as_receiver(&self) -> Result<&IScriptable, InvokeError> { 435 | unsafe { self.instance() } 436 | .map(AsRef::as_ref) 437 | .ok_or(InvokeError::NullReceiver(T::NAME)) 438 | } 439 | } 440 | 441 | #[sealed] 442 | impl AsReceiver for &Ref 443 | where 444 | >::NativeType: AsRef, 445 | { 446 | #[inline] 447 | fn as_receiver(&self) -> Result<&IScriptable, InvokeError> { 448 | as AsReceiver>::as_receiver(*self) 449 | } 450 | } 451 | 452 | #[sealed] 453 | #[doc(hidden)] 454 | pub trait Args { 455 | type Array<'a>: AsRef<[StackArg<'a>]> 456 | where 457 | Self: 'a; 458 | 459 | fn to_array(&mut self) -> Result, InvokeError>; 460 | } 461 | 462 | macro_rules! impl_args { 463 | ($( ($( $ids:ident ),*) ),*) => { 464 | $( 465 | #[allow(unused_parens, non_snake_case)] 466 | #[sealed] 467 | impl <$($ids: NativeRepr),*> Args for ($($ids,)*) { 468 | type Array<'a> = [StackArg<'a>; count_args!($($ids)*)] where Self: 'a; 469 | 470 | #[inline] 471 | fn to_array(&mut self) -> Result, InvokeError> { 472 | let ($($ids,)*) = self; 473 | Ok([$( 474 | StackArg::new($ids).ok_or_else(|| 475 | InvokeError::UnresolvedType($ids::NAME) 476 | )?),* 477 | ]) 478 | } 479 | } 480 | )* 481 | }; 482 | } 483 | 484 | macro_rules! count_args { 485 | ($id:ident $( $t:tt )*) => { 486 | 1 + count_args!($($t)*) 487 | }; 488 | () => { 0 } 489 | } 490 | 491 | impl_args!( 492 | (), 493 | (A), 494 | (A, B), 495 | (A, B, C), 496 | (A, B, C, D), 497 | (A, B, C, D, E), 498 | (A, B, C, D, E, F), 499 | (A, B, C, D, E, F, G) 500 | ); 501 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![allow(clippy::missing_safety_doc)] 3 | use std::ffi::CString; 4 | use std::sync::OnceLock; 5 | use std::{ffi, fmt, mem}; 6 | 7 | pub use export::{ 8 | ClassExport, ClassExportBuilder, ExportList, ExportNil, Exportable, GlobalExport, StructExport, 9 | StructExportBuilder, 10 | }; 11 | use raw::root::{RED4ext as red, versioning}; 12 | use sealed::sealed; 13 | use types::StaticArray; 14 | pub use widestring::{U16CStr, widecstr as wcstr}; 15 | 16 | mod class; 17 | mod export; 18 | mod invocable; 19 | mod raw; 20 | mod repr; 21 | mod systems; 22 | 23 | /// A module encapsulating various types defined in the RED4ext SDK. 24 | pub mod types; 25 | 26 | pub use class::{ClassKind, ScriptClass, ScriptClassOps, class_kind}; 27 | pub use invocable::{ 28 | AsReceiver, FunctionType, GlobalInvocable, GlobalMetadata, InvokeError, MethodInvocable, 29 | MethodMetadata, 30 | }; 31 | pub use repr::{FromRepr, IntoRepr, NativeRepr}; 32 | pub use systems::{RttiRegistrator, RttiSystem, RttiSystemMut}; 33 | 34 | /// Hashes of known function addresses. 35 | /// 36 | /// # Example 37 | /// Resolve a hash to an address: 38 | /// ```rust 39 | /// use red4ext_rs::addr_hashes; 40 | /// 41 | /// fn exec_hash() -> usize { 42 | /// addr_hashes::resolve(addr_hashes::CBaseFunction_ExecuteNative) 43 | /// } 44 | pub mod addr_hashes { 45 | pub use super::red::Detail::AddressHashes::*; 46 | 47 | /// Resolves a hash to an address. 48 | #[inline] 49 | pub fn resolve(hash: u32) -> usize { 50 | unsafe { super::red::UniversalRelocBase::Resolve(hash) } 51 | } 52 | } 53 | 54 | #[doc(hidden)] 55 | pub mod internal { 56 | pub use crate::red::{EMainReason, PluginHandle, PluginInfo, Sdk}; 57 | } 58 | 59 | #[doc(hidden)] 60 | pub type VoidPtr = *mut std::os::raw::c_void; 61 | 62 | /// A definition of a RED4ext plugin. 63 | pub trait Plugin { 64 | /// The name of the plugin. 65 | const NAME: &'static U16CStr; 66 | /// The author of the plugin. 67 | const AUTHOR: &'static U16CStr; 68 | /// The version of the plugin. 69 | const VERSION: SemVer; 70 | /// The RED4ext SDK version the plugin was built with. 71 | const SDK: SdkVersion = SdkVersion::LATEST; 72 | /// The version of the game the plugin is compatible with. 73 | const RUNTIME: RuntimeVersion = RuntimeVersion::RUNTIME_INDEPENDENT; 74 | /// The RED4ext API version. 75 | const API_VERSION: ApiVersion = ApiVersion::LATEST; 76 | 77 | /// A list of definitions to be exported automatically when the plugin is loaded. 78 | /// This can be used to define classes and functions that will available to use in the game. 79 | /// See the [`exports!`] macro for more information. 80 | fn exports() -> impl Exportable { 81 | ExportNil 82 | } 83 | 84 | /// A function that is called when the plugin is initialized. 85 | fn on_init(_env: &SdkEnv) {} 86 | } 87 | 88 | /// A set of useful operations that can be performed on a plugin. 89 | #[sealed] 90 | pub trait PluginOps: Plugin { 91 | /// Retrieves a statically initialized reference to the plugin environment. 92 | /// It can be used to log messages, add state listeners, and attach hooks. 93 | fn env() -> &'static SdkEnv; 94 | 95 | #[doc(hidden)] 96 | fn env_lock() -> &'static OnceLock>; 97 | #[doc(hidden)] 98 | fn info() -> PluginInfo; 99 | #[doc(hidden)] 100 | fn init(env: SdkEnv); 101 | } 102 | 103 | #[sealed] 104 | impl

PluginOps for P 105 | where 106 | P: Plugin, 107 | { 108 | fn env() -> &'static SdkEnv { 109 | Self::env_lock().get().unwrap() 110 | } 111 | 112 | #[inline] 113 | fn env_lock() -> &'static OnceLock> { 114 | static ENV: OnceLock> = OnceLock::new(); 115 | &ENV 116 | } 117 | 118 | #[inline] 119 | fn info() -> PluginInfo { 120 | PluginInfo::new( 121 | Self::NAME, 122 | Self::AUTHOR, 123 | Self::SDK, 124 | Self::VERSION, 125 | Self::RUNTIME, 126 | ) 127 | } 128 | 129 | fn init(env: SdkEnv) { 130 | Self::env_lock() 131 | .set(Box::new(env)) 132 | .expect("plugin environment should not be initialized"); 133 | 134 | #[cfg(feature = "log")] 135 | { 136 | log::set_logger(Self::env()).unwrap(); 137 | log::set_max_level(log::LevelFilter::Trace); 138 | } 139 | 140 | Self::on_init(Self::env()); 141 | } 142 | } 143 | 144 | /// Defines a set of DLL symbols necessary for RED4ext to load the plugin. Your plugin will 145 | /// not be loaded unless you call this macro. 146 | #[macro_export] 147 | macro_rules! export_plugin_symbols { 148 | ($trait:ty) => { 149 | // The exports will not work in tests, so they are disabled here. 150 | #[cfg(not(test))] 151 | mod __api { 152 | use super::*; 153 | 154 | #[unsafe(no_mangle)] 155 | #[allow(non_snake_case, unused_variables)] 156 | unsafe extern "C" fn Query(info: *mut $crate::internal::PluginInfo) { 157 | *info = <$trait as $crate::PluginOps>::info().into_raw(); 158 | } 159 | 160 | #[unsafe(no_mangle)] 161 | #[allow(non_snake_case, unused_variables)] 162 | extern "C" fn Main( 163 | handle: $crate::internal::PluginHandle, 164 | reason: $crate::internal::EMainReason::Type, 165 | sdk: $crate::internal::Sdk, 166 | ) { 167 | if reason == $crate::internal::EMainReason::Load { 168 | <$trait as $crate::PluginOps>::init($crate::SdkEnv::new(handle, sdk)); 169 | $crate::RttiRegistrator::add(Some(on_register), Some(on_post_register)); 170 | } 171 | } 172 | 173 | #[unsafe(no_mangle)] 174 | #[allow(non_snake_case, unused_variables)] 175 | extern "C" fn Supports() -> u32 { 176 | ::std::convert::Into::into(<$trait as $crate::Plugin>::API_VERSION) 177 | } 178 | 179 | extern "C" fn on_register() { 180 | let exports = <$trait as $crate::Plugin>::exports(); 181 | $crate::Exportable::register(&exports); 182 | } 183 | 184 | extern "C" fn on_post_register() { 185 | let exports = <$trait as $crate::Plugin>::exports(); 186 | $crate::Exportable::post_register(&exports); 187 | } 188 | } 189 | }; 190 | } 191 | 192 | /// Convenience logging macros. By default all macros require a [`SdkEnv`] instance to be passed as 193 | /// the first argument. If the `log` feature is enabled, this module becomes an alias to the 194 | /// `log` crate. 195 | #[cfg(not(feature = "log"))] 196 | pub mod log { 197 | #[doc(inline)] 198 | pub use crate::{ 199 | __debug as debug, __error as error, __info as info, __trace as trace, __warn as warn, 200 | }; 201 | 202 | /// Logs a message at the info level. 203 | /// 204 | /// # Example 205 | /// ```rust 206 | /// use red4ext_rs::{SdkEnv, log}; 207 | /// 208 | /// fn log_info(env: &SdkEnv) { 209 | /// log::info!(env, "Hello, world!"); 210 | /// // log::info!("Hello, world!"); // if the `log` feature is enabled 211 | /// } 212 | /// ``` 213 | #[doc(hidden)] 214 | #[macro_export] 215 | macro_rules! __info { 216 | ($env:expr, $($arg:tt)*) => { 217 | $env.info(format_args!($($arg)*)) 218 | }; 219 | } 220 | 221 | /// Logs a message at the warn level. 222 | /// 223 | /// # Example 224 | /// ```rust 225 | /// use red4ext_rs::{SdkEnv, log}; 226 | /// 227 | /// fn log_warn(env: &SdkEnv) { 228 | /// log::warn!(env, "Hello, world!"); 229 | /// // log::warn!("Hello, world!"); // if the `log` feature is enabled 230 | /// } 231 | /// ``` 232 | #[doc(hidden)] 233 | #[macro_export] 234 | macro_rules! __warn { 235 | ($env:expr, $($arg:tt)*) => { 236 | $env.warn(format_args!($($arg)*)) 237 | }; 238 | } 239 | 240 | /// Logs a message at the error level. 241 | /// 242 | /// # Example 243 | /// ```rust 244 | /// use red4ext_rs::{SdkEnv, log}; 245 | /// 246 | /// fn log_error(env: &SdkEnv) { 247 | /// log::error!(env, "Hello, world!"); 248 | /// // log::error!("Hello, world!"); // if the `log` feature is enabled 249 | /// } 250 | /// ``` 251 | #[doc(hidden)] 252 | #[macro_export] 253 | macro_rules! __error { 254 | ($env:expr, $($arg:tt)*) => { 255 | $env.error(format_args!($($arg)*)) 256 | }; 257 | } 258 | 259 | /// Logs a message at the debug level. 260 | /// 261 | /// # Example 262 | /// ```rust 263 | /// use red4ext_rs::{SdkEnv, log}; 264 | /// 265 | /// fn log_debug(env: &SdkEnv) { 266 | /// log::debug!(env, "Hello, world!"); 267 | /// // log::debug!("Hello, world!"); // if the `log` feature is enabled 268 | /// } 269 | /// ``` 270 | #[doc(hidden)] 271 | #[macro_export] 272 | macro_rules! __debug { 273 | ($env:expr, $($arg:tt)*) => { 274 | $env.debug(format_args!($($arg)*)) 275 | }; 276 | } 277 | 278 | /// Logs a message at the trace level. 279 | /// 280 | /// # Example 281 | /// ```rust 282 | /// use red4ext_rs::{SdkEnv, log}; 283 | /// 284 | /// fn log_trace(env: &SdkEnv) { 285 | /// log::trace!(env, "Hello, world!"); 286 | /// // log::trace!("Hello, world!"); // if the `log` feature is enabled 287 | /// } 288 | /// ``` 289 | #[doc(hidden)] 290 | #[macro_export] 291 | macro_rules! __trace { 292 | ($env:expr, $($arg:tt)*) => { 293 | $env.trace(format_args!($($arg)*)) 294 | }; 295 | } 296 | } 297 | 298 | #[cfg(feature = "log")] 299 | pub use log; 300 | 301 | macro_rules! log_internal { 302 | ($self:ident, $level:ident, $msg:expr) => { 303 | unsafe { 304 | let str = truncated_cstring($msg.to_string()); 305 | ((*$self.sdk.logger).$level.unwrap())($self.handle, str.as_ptr()); 306 | } 307 | }; 308 | } 309 | 310 | /// A handle to the RED4ext SDK environment. 311 | /// This struct enables access to the SDK's functions and logging facilities. 312 | /// It can be obtained statically using the [`PluginOps::env`] method from any plugin 313 | /// implementation. 314 | #[derive(Debug)] 315 | pub struct SdkEnv { 316 | handle: red::PluginHandle, 317 | sdk: red::Sdk, 318 | } 319 | 320 | impl SdkEnv { 321 | #[doc(hidden)] 322 | pub fn new(handle: red::PluginHandle, sdk: red::Sdk) -> Self { 323 | Self { handle, sdk } 324 | } 325 | 326 | /// Logs a message at the info level. 327 | /// You should generally use the [`info!`](crate::log::info) macro instead of calling this method directly. 328 | #[inline] 329 | pub fn info(&self, txt: impl fmt::Display) { 330 | log_internal!(self, Info, txt); 331 | } 332 | 333 | /// Logs a message at the warn level. 334 | /// You should generally use the [`warn!`](crate::log::warn) macro instead of calling this method directly. 335 | #[inline] 336 | pub fn warn(&self, txt: impl fmt::Display) { 337 | log_internal!(self, Warn, txt); 338 | } 339 | 340 | /// Logs a message at the error level. 341 | /// You should generally use the [`error!`](crate::log::error) macro instead of calling this method directly. 342 | #[inline] 343 | pub fn error(&self, txt: impl fmt::Display) { 344 | log_internal!(self, Error, txt); 345 | } 346 | 347 | /// Logs a message at the debug level. 348 | /// You should generally use the [`debug!`](crate::log::debug) macro instead of calling this method directly. 349 | #[inline] 350 | pub fn debug(&self, txt: impl fmt::Display) { 351 | log_internal!(self, Debug, txt); 352 | } 353 | 354 | /// Logs a message at the trace level. 355 | /// You should generally use the [`trace!`](crate::log::trace) macro instead of calling this method directly. 356 | #[inline] 357 | pub fn trace(&self, txt: impl fmt::Display) { 358 | log_internal!(self, Trace, txt); 359 | } 360 | 361 | /// Adds a listener to a specific state type. 362 | /// The listener will be called when the state is entered, updated, or exited. 363 | /// See [`StateType`] for the available state types. 364 | /// 365 | /// # Example 366 | /// ```rust 367 | /// use red4ext_rs::{GameApp, SdkEnv, StateListener, StateType}; 368 | /// 369 | /// fn add_state_listener(env: &SdkEnv) { 370 | /// let listener = StateListener::default() 371 | /// .with_on_enter(on_enter) 372 | /// .with_on_exit(on_exit); 373 | /// env.add_listener(StateType::Running, listener); 374 | /// } 375 | /// 376 | /// unsafe extern "C" fn on_enter(app: &GameApp) { 377 | /// // do something here... 378 | /// } 379 | /// 380 | /// unsafe extern "C" fn on_exit(app: &GameApp) { 381 | /// // do something here... 382 | /// } 383 | /// ``` 384 | #[inline] 385 | pub fn add_listener(&self, typ: StateType, mut listener: StateListener) -> bool { 386 | unsafe { ((*self.sdk.gameStates).Add.unwrap())(self.handle, typ as u32, &mut listener.0) } 387 | } 388 | 389 | /// Attaches a hook to a target function. 390 | /// The hook will be called instead of the target function. The hook must accept a callback 391 | /// function as its last argument, which should be called to execute the original function. 392 | /// 393 | /// # Safety 394 | /// The target and detour functions must both be valid and compatible function pointers. 395 | /// 396 | /// # Example 397 | /// ```rust 398 | /// use red4ext_rs::{SdkEnv, hooks}; 399 | /// 400 | /// hooks! { 401 | /// static ADD_HOOK: fn(a: u32, b: u32) -> u32; 402 | /// } 403 | /// 404 | /// fn attach_my_hook(env: &SdkEnv, addr: unsafe extern "C" fn(u32, u32) -> u32) { 405 | /// unsafe { env.attach_hook(ADD_HOOK, addr, detour) }; 406 | /// } 407 | /// 408 | /// unsafe extern "C" fn detour(a: u32, b: u32, cb: unsafe extern "C" fn(u32, u32) -> u32) -> u32 { 409 | /// // do something here... 410 | /// cb(a, b) 411 | /// } 412 | /// ``` 413 | pub unsafe fn attach_hook( 414 | &self, 415 | hook: *mut Hook, 416 | target: F1, 417 | detour: F2, 418 | ) -> bool 419 | where 420 | F1: FnPtr, 421 | F2: FnPtr, 422 | { 423 | unsafe { 424 | let Hook(original, cb_ref, detour_ref) = &*hook; 425 | detour_ref.replace(Some(detour)); 426 | 427 | ((*self.sdk.hooking).Attach.unwrap())( 428 | self.handle, 429 | target.to_ptr(), 430 | original.to_ptr(), 431 | (*cb_ref).cast::(), 432 | ) 433 | } 434 | } 435 | 436 | /// Detaches a hook from a target function. 437 | #[inline] 438 | pub unsafe fn detach_hook(&self, target: F) -> bool 439 | where 440 | F: FnPtr, 441 | { 442 | unsafe { ((*self.sdk.hooking).Detach.unwrap())(self.handle, target.to_ptr()) } 443 | } 444 | } 445 | 446 | unsafe impl Send for SdkEnv {} 447 | unsafe impl Sync for SdkEnv {} 448 | 449 | #[cfg(feature = "log")] 450 | impl log::Log for SdkEnv { 451 | fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool { 452 | true 453 | } 454 | 455 | fn log(&self, record: &log::Record<'_>) { 456 | match record.level() { 457 | log::Level::Error => self.error(record.args()), 458 | log::Level::Warn => self.warn(record.args()), 459 | log::Level::Info => self.info(record.args()), 460 | log::Level::Debug => self.debug(record.args()), 461 | log::Level::Trace => self.trace(record.args()), 462 | }; 463 | } 464 | 465 | fn flush(&self) {} 466 | } 467 | 468 | /// A version number in the semantic versioning format. 469 | #[derive(Debug)] 470 | pub struct SemVer(red::SemVer); 471 | 472 | impl SemVer { 473 | /// Creates a new semantic version. 474 | #[inline] 475 | pub const fn new(major: u8, minor: u16, patch: u32) -> Self { 476 | Self::exact(major, minor, patch, 0, 0) 477 | } 478 | 479 | /// Creates a new exact semantic version. 480 | #[inline] 481 | pub const fn exact(major: u8, minor: u16, patch: u32, type_: u32, number: u32) -> Self { 482 | Self(red::SemVer { 483 | major, 484 | minor, 485 | patch, 486 | prerelease: red::v0::SemVer_PrereleaseInfo { type_, number }, 487 | }) 488 | } 489 | } 490 | 491 | impl From for StaticArray { 492 | fn from(value: SemVer) -> Self { 493 | Self::from([value.0.major as u16, value.0.minor, value.0.patch as u16]) 494 | } 495 | } 496 | 497 | impl From for StaticArray { 498 | fn from(value: SemVer) -> Self { 499 | Self::from([ 500 | value.0.major as u16, 501 | value.0.minor, 502 | value.0.patch as u16, 503 | value.0.prerelease.type_ as u16, 504 | value.0.prerelease.number as u16, 505 | ]) 506 | } 507 | } 508 | 509 | impl IntoRepr for SemVer { 510 | type Repr = StaticArray; 511 | 512 | fn into_repr(self) -> Self::Repr { 513 | Self::Repr::from([self.0.major as u16, self.0.minor, self.0.patch as u16]) 514 | } 515 | } 516 | 517 | /// A version number representing the game's version. 518 | #[derive(Debug)] 519 | pub struct RuntimeVersion(red::FileVer); 520 | 521 | impl RuntimeVersion { 522 | /// A special version number that indicates the plugin is compatible with any game version. 523 | pub const RUNTIME_INDEPENDENT: Self = Self(red::FileVer { 524 | major: versioning::RUNTIME_INDEPENDENT, 525 | minor: versioning::RUNTIME_INDEPENDENT, 526 | build: versioning::RUNTIME_INDEPENDENT, 527 | revision: versioning::RUNTIME_INDEPENDENT, 528 | }); 529 | } 530 | 531 | /// A version number representing the RED4ext SDK version. 532 | #[derive(Debug)] 533 | pub struct SdkVersion(SemVer); 534 | 535 | impl SdkVersion { 536 | /// The latest version of the RED4ext SDK compatible with this version of the library. 537 | pub const LATEST: Self = Self(SemVer::new( 538 | versioning::SDK_MAJOR, 539 | versioning::SDK_MINOR, 540 | versioning::SDK_PATCH, 541 | )); 542 | } 543 | 544 | /// A version number representing the RED4ext API version. 545 | #[derive(Debug)] 546 | pub struct ApiVersion(u32); 547 | 548 | impl ApiVersion { 549 | /// The latest version of the RED4ext API compatible with this version of the library. 550 | pub const LATEST: Self = Self(versioning::API_VERSION_LATEST); 551 | } 552 | 553 | impl From for u32 { 554 | #[inline] 555 | fn from(api: ApiVersion) -> u32 { 556 | api.0 557 | } 558 | } 559 | 560 | /// Defines a set of hooks that can be attached to target functions. 561 | /// The hooks are defined as static variables and must be initialized with a call to 562 | /// [`SdkEnv::attach_hook`]. 563 | /// 564 | /// # Example 565 | /// ```rust 566 | /// use red4ext_rs::hooks; 567 | /// 568 | /// hooks! { 569 | /// static ADD_HOOK: fn(a: u32, b: u32) -> u32; 570 | /// } 571 | /// ``` 572 | #[macro_export] 573 | macro_rules! hooks { 574 | ($(static $name:ident: fn($($arg:ident: $ty:ty),*) -> $ret:ty;)*) => {$( 575 | static mut $name: *mut $crate::Hook< 576 | unsafe extern "C" fn($($arg: $ty),*) -> $ret, 577 | unsafe extern "C" fn($($arg: $ty),*, cb: unsafe extern "C" fn($($arg: $ty),*) -> $ret) -> $ret 578 | > = unsafe { 579 | 580 | static mut TARGET: Option $ret> = None; 581 | static mut DETOUR: Option $ret) -> $ret> = None; 582 | 583 | unsafe extern "C" fn internal($($arg: $ty),*) -> $ret { 584 | let target = unsafe { TARGET.expect("target function should be set") }; 585 | let detour = unsafe { DETOUR.expect("detour function should be set") }; 586 | detour($($arg,)* target) 587 | } 588 | 589 | static mut HOOK: $crate::Hook< 590 | unsafe extern "C" fn($($arg: $ty),*) -> $ret, 591 | unsafe extern "C" fn($($arg: $ty),*, cb: unsafe extern "C" fn($($arg: $ty),*) -> $ret) -> $ret 592 | > = unsafe { $crate::Hook::new(internal, ::std::ptr::addr_of_mut!(TARGET), ::std::ptr::addr_of_mut!(DETOUR)) }; 593 | 594 | ::std::ptr::addr_of_mut!(HOOK) 595 | }; 596 | )*}; 597 | } 598 | 599 | /// A wrapper around function pointers that can be passed to [`SdkEnv::attach_hook`] to install 600 | /// detours. 601 | #[derive(Debug)] 602 | pub struct Hook(O, *mut Option, *mut Option); 603 | 604 | #[doc(hidden)] 605 | impl Hook { 606 | #[inline] 607 | pub const fn new(original: O, cb_ref: *mut Option, detour_ref: *mut Option) -> Self { 608 | Self(original, cb_ref, detour_ref) 609 | } 610 | } 611 | 612 | /// A trait for functions that are convertible to pointers. Only non-closure functions can 613 | /// satisfy this requirement. 614 | #[sealed] 615 | pub trait FnPtr { 616 | fn to_ptr(&self) -> VoidPtr; 617 | } 618 | 619 | macro_rules! impl_fn_ptr { 620 | ($($ty:ident),*) => { 621 | #[sealed] 622 | impl <$($ty,)* Ret> FnPtr<($($ty,)*), Ret> for unsafe extern "C" fn($($ty,)*) -> Ret { 623 | #[inline] 624 | fn to_ptr(&self) -> VoidPtr { 625 | *self as _ 626 | } 627 | } 628 | } 629 | } 630 | 631 | impl_fn_ptr!(); 632 | impl_fn_ptr!(A); 633 | impl_fn_ptr!(A, B); 634 | impl_fn_ptr!(A, B, C); 635 | impl_fn_ptr!(A, B, C, D); 636 | impl_fn_ptr!(A, B, C, D, E); 637 | impl_fn_ptr!(A, B, C, D, E, F); 638 | impl_fn_ptr!(A, B, C, D, E, F, G); 639 | impl_fn_ptr!(A, B, C, D, E, F, G, H); 640 | 641 | /// A callback function to be called when a state is entered, updated, or exited. 642 | pub type StateHandler = unsafe extern "C" fn(app: &GameApp); 643 | 644 | /// A wrapper around the game application instance. 645 | #[repr(transparent)] 646 | pub struct GameApp(red::CGameApplication); 647 | 648 | /// A listener for state changes in the game application. 649 | /// The listener can be attached to a specific state type using the [`SdkEnv::add_listener`] 650 | /// method. 651 | #[derive(Debug, Default)] 652 | #[repr(transparent)] 653 | pub struct StateListener(red::GameState); 654 | 655 | #[allow(clippy::missing_transmute_annotations)] 656 | impl StateListener { 657 | /// Sets a callback to be called when the state is entered. 658 | #[inline] 659 | pub fn with_on_enter(self, cb: StateHandler) -> Self { 660 | Self(red::GameState { 661 | OnEnter: Some(unsafe { mem::transmute(cb) }), 662 | ..self.0 663 | }) 664 | } 665 | 666 | /// Sets a callback to be called when the state is updated. 667 | #[inline] 668 | pub fn with_on_update(self, cb: StateHandler) -> Self { 669 | Self(red::GameState { 670 | OnUpdate: Some(unsafe { mem::transmute(cb) }), 671 | ..self.0 672 | }) 673 | } 674 | 675 | /// Sets a callback to be called when the state is exited. 676 | #[inline] 677 | pub fn with_on_exit(self, cb: StateHandler) -> Self { 678 | Self(red::GameState { 679 | OnExit: Some(unsafe { mem::transmute(cb) }), 680 | ..self.0 681 | }) 682 | } 683 | } 684 | 685 | /// An enum representing different types of game states. 686 | #[derive(Debug)] 687 | #[repr(u32)] 688 | pub enum StateType { 689 | BaseInitialization = red::EGameStateType::BaseInitialization, 690 | Initialization = red::EGameStateType::Initialization, 691 | Running = red::EGameStateType::Running, 692 | Shutdown = red::EGameStateType::Shutdown, 693 | } 694 | 695 | /// Information about a plugin. 696 | #[derive(Debug)] 697 | #[doc(hidden)] 698 | #[repr(transparent)] 699 | pub struct PluginInfo(red::PluginInfo); 700 | 701 | impl PluginInfo { 702 | #[doc(hidden)] 703 | #[inline] 704 | pub const fn new( 705 | name: &'static U16CStr, 706 | author: &'static U16CStr, 707 | sdk: SdkVersion, 708 | version: SemVer, 709 | runtime: RuntimeVersion, 710 | ) -> Self { 711 | Self(red::PluginInfo { 712 | name: name.as_ptr(), 713 | author: author.as_ptr(), 714 | sdk: sdk.0.0, 715 | version: version.0, 716 | runtime: runtime.0, 717 | }) 718 | } 719 | 720 | #[doc(hidden)] 721 | #[inline] 722 | pub fn into_raw(self) -> red::PluginInfo { 723 | self.0 724 | } 725 | } 726 | 727 | const fn fnv1a64(str: &[u8]) -> u64 { 728 | const PRIME: u64 = 0x0100_0000_01b3; 729 | const SEED: u64 = 0xCBF2_9CE4_8422_2325; 730 | 731 | let mut tail = str; 732 | let mut hash = SEED; 733 | loop { 734 | match tail.split_first() { 735 | Some((head, rem)) => { 736 | hash ^= *head as u64; 737 | hash = hash.wrapping_mul(PRIME); 738 | tail = rem; 739 | } 740 | None => break hash, 741 | } 742 | } 743 | } 744 | 745 | const fn fnv1a32(str: &str) -> u32 { 746 | const PRIME: u32 = 0x0100_0193; 747 | const SEED: u32 = 0x811C_9DC5; 748 | 749 | let mut tail = str.as_bytes(); 750 | let mut hash = SEED; 751 | loop { 752 | match tail.split_first() { 753 | Some((head, rem)) => { 754 | hash ^= *head as u32; 755 | hash = hash.wrapping_mul(PRIME); 756 | tail = rem; 757 | } 758 | None => break hash, 759 | } 760 | } 761 | } 762 | 763 | fn truncated_cstring(mut s: String) -> ffi::CString { 764 | s.truncate(s.find('\0').unwrap_or(s.len())); 765 | unsafe { CString::from_vec_unchecked(s.into_bytes()) } 766 | } 767 | 768 | macro_rules! fn_from_hash { 769 | ($name:ident, $ty:ty) => {{ 770 | $crate::fn_from_hash!($name, $ty, offset: 0) 771 | }}; 772 | ($name:ident, $ty:ty, offset: $offset:expr) => {{ 773 | unsafe fn inner() -> $ty { 774 | static STATIC: ::once_cell::race::OnceNonZeroUsize = 775 | ::once_cell::race::OnceNonZeroUsize::new(); 776 | let addr = STATIC 777 | .get_or_try_init(|| { 778 | ::std::num::NonZero::new($crate::addr_hashes::resolve($crate::addr_hashes::$name)).ok_or(()) 779 | }) 780 | .expect(::std::stringify!(should resolve $name hash)) 781 | .get(); 782 | unsafe { 783 | ::std::mem::transmute::(addr + $offset) 784 | } 785 | } 786 | inner() 787 | }}; 788 | } 789 | 790 | pub(crate) use fn_from_hash; 791 | 792 | #[cold] 793 | #[track_caller] 794 | fn check_invariant(success: bool, message: &'static str) { 795 | #[cfg(feature = "log")] 796 | if !success { 797 | log::error!( 798 | "invariant violated: {message}: {}", 799 | std::panic::Location::caller(), 800 | ); 801 | } 802 | assert!(success, "{message}"); 803 | } 804 | -------------------------------------------------------------------------------- /src/raw.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_upper_case_globals)] 2 | #![allow(non_camel_case_types)] 3 | #![allow(non_snake_case)] 4 | #![allow(unused)] 5 | #![allow(improper_ctypes)] 6 | #![allow(unsafe_op_in_unsafe_fn)] 7 | #![allow(clippy::all)] 8 | include!(concat!(env!("OUT_DIR"), "/bindings.rs")); 9 | -------------------------------------------------------------------------------- /src/repr.rs: -------------------------------------------------------------------------------- 1 | use const_combine::bounded::const_combine as combine; 2 | 3 | use crate::class::ScriptClass; 4 | use crate::types::{ 5 | CName, EntityId, GameTime, ItemId, Opt, RedArray, RedString, Ref, ScriptRef, TweakDbId, 6 | Variant, WeakRef, 7 | }; 8 | 9 | /// A trait for types that can be passed across the FFI boundary to the game engine without 10 | /// any conversion. 11 | /// 12 | /// # Safety 13 | /// 14 | /// Implementations of this trait are only valid if the memory representation of Self 15 | /// is idetical to the representation of type with name Self::NAME in-game. 16 | pub unsafe trait NativeRepr { 17 | const NAME: &'static str; 18 | } 19 | 20 | unsafe impl NativeRepr for () { 21 | const NAME: &'static str = "Void"; 22 | } 23 | 24 | unsafe impl NativeRepr for RedString { 25 | const NAME: &'static str = "String"; 26 | } 27 | 28 | unsafe impl NativeRepr for RedArray { 29 | const NAME: &'static str = combine!("array:", A::NAME); 30 | } 31 | 32 | unsafe impl NativeRepr for Ref { 33 | const NAME: &'static str = combine!("handle:", A::NAME); 34 | } 35 | 36 | unsafe impl NativeRepr for WeakRef { 37 | const NAME: &'static str = combine!("whandle:", A::NAME); 38 | } 39 | 40 | unsafe impl NativeRepr for ScriptRef<'_, A> { 41 | const NAME: &'static str = combine!("script_ref:", A::NAME); 42 | } 43 | 44 | macro_rules! impl_native_repr { 45 | ($ty:ty, $name:literal) => { 46 | unsafe impl NativeRepr for $ty { 47 | const NAME: &'static str = $name; 48 | } 49 | }; 50 | ($ty:ty, $name:literal, $native_name:literal) => { 51 | unsafe impl NativeRepr for $ty { 52 | const NAME: &'static str = $native_name; 53 | } 54 | }; 55 | } 56 | 57 | impl_native_repr!(f32, "Float"); 58 | impl_native_repr!(f64, "Double"); 59 | impl_native_repr!(i64, "Int64"); 60 | impl_native_repr!(i32, "Int32"); 61 | impl_native_repr!(i16, "Int16"); 62 | impl_native_repr!(i8, "Int8"); 63 | impl_native_repr!(u64, "Uint64"); 64 | impl_native_repr!(u32, "Uint32"); 65 | impl_native_repr!(u16, "Uint16"); 66 | impl_native_repr!(u8, "Uint8"); 67 | impl_native_repr!(bool, "Bool"); 68 | impl_native_repr!(CName, "CName"); 69 | impl_native_repr!(TweakDbId, "TweakDBID"); 70 | impl_native_repr!(ItemId, "ItemID", "gameItemID"); 71 | impl_native_repr!(EntityId, "EntityID", "entEntityID"); 72 | impl_native_repr!(GameTime, "GameTime", "GameTime"); 73 | impl_native_repr!(Variant, "Variant", "Variant"); 74 | 75 | /// A trait for types that can be converted into a representation that can be passed across 76 | /// the FFI boundary to the game. 77 | pub trait IntoRepr: Sized { 78 | type Repr: NativeRepr; 79 | 80 | fn into_repr(self) -> Self::Repr; 81 | } 82 | 83 | impl IntoRepr for A { 84 | type Repr = A; 85 | 86 | #[inline] 87 | fn into_repr(self) -> Self::Repr { 88 | self 89 | } 90 | } 91 | 92 | impl IntoRepr for String { 93 | type Repr = RedString; 94 | 95 | #[inline] 96 | fn into_repr(self) -> Self::Repr { 97 | RedString::from(self) 98 | } 99 | } 100 | 101 | impl IntoRepr for &str { 102 | type Repr = RedString; 103 | 104 | #[inline] 105 | fn into_repr(self) -> Self::Repr { 106 | RedString::from(self) 107 | } 108 | } 109 | 110 | impl IntoRepr for Vec 111 | where 112 | A: IntoRepr, 113 | { 114 | type Repr = RedArray; 115 | 116 | fn into_repr(self) -> Self::Repr { 117 | self.into_iter().map(IntoRepr::into_repr).collect() 118 | } 119 | } 120 | 121 | impl IntoRepr for Opt { 122 | type Repr = A; 123 | 124 | #[inline] 125 | fn into_repr(self) -> Self::Repr { 126 | match self { 127 | Self::Default => A::default(), 128 | Self::NonDefault(x) => x, 129 | } 130 | } 131 | } 132 | 133 | /// A trait for types that can be created from a representation passed across the FFI boundary. 134 | pub trait FromRepr: Sized { 135 | type Repr: NativeRepr; 136 | 137 | fn from_repr(repr: Self::Repr) -> Self; 138 | } 139 | 140 | impl FromRepr for A { 141 | type Repr = A; 142 | 143 | #[inline] 144 | fn from_repr(repr: Self::Repr) -> Self { 145 | repr 146 | } 147 | } 148 | 149 | impl FromRepr for String { 150 | type Repr = RedString; 151 | 152 | #[inline] 153 | fn from_repr(repr: Self::Repr) -> Self { 154 | repr.into() 155 | } 156 | } 157 | 158 | impl FromRepr for Vec 159 | where 160 | A: FromRepr, 161 | { 162 | type Repr = RedArray; 163 | 164 | fn from_repr(repr: Self::Repr) -> Self { 165 | repr.into_iter().map(FromRepr::from_repr).collect() 166 | } 167 | } 168 | 169 | impl FromRepr for Opt { 170 | type Repr = A; 171 | 172 | fn from_repr(repr: Self::Repr) -> Self { 173 | let repr = A::from_repr(repr); 174 | if repr == A::default() { 175 | return Self::Default; 176 | } 177 | Self::NonDefault(repr) 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/systems.rs: -------------------------------------------------------------------------------- 1 | mod rtti; 2 | pub use rtti::{RttiRegistrator, RttiSystem, RttiSystemMut}; 3 | -------------------------------------------------------------------------------- /src/systems/rtti.rs: -------------------------------------------------------------------------------- 1 | use std::{mem, ptr}; 2 | 3 | use crate::raw::root::RED4ext as red; 4 | use crate::types::{ 5 | Bitfield, CName, Class, ClassFlags, ClassHandle, Enum, Function, GameEngine, GlobalFunction, 6 | PoolRef, RedArray, RedHashMap, Ref, RwSpinLockReadGuard, RwSpinLockWriteGuard, 7 | ScriptableSystem, Type, 8 | }; 9 | 10 | /// The RTTI system containing information about all types in the game. 11 | /// 12 | /// # Example 13 | /// ```rust 14 | /// use red4ext_rs::RttiSystem; 15 | /// use red4ext_rs::types::CName; 16 | /// 17 | /// fn rtti_example() { 18 | /// let rtti = RttiSystem::get(); 19 | /// let class = rtti.get_class(CName::new("IScriptable")).unwrap(); 20 | /// for method in class.methods() { 21 | /// // do something with the method 22 | /// } 23 | /// } 24 | /// ``` 25 | #[repr(transparent)] 26 | pub struct RttiSystem(red::CRTTISystem); 27 | 28 | impl RttiSystem { 29 | /// Acquire a read lock on the RTTI system. 30 | #[inline] 31 | pub fn get<'a>() -> RwSpinLockReadGuard<'a, Self> { 32 | unsafe { 33 | let rtti = red::CRTTISystem_Get(); 34 | let lock = &(*rtti).typesLock; 35 | RwSpinLockReadGuard::new(lock, ptr::NonNull::new_unchecked(rtti as _)) 36 | } 37 | } 38 | 39 | /// Retrieve a class by its name. 40 | #[inline] 41 | pub fn get_class(&self, name: CName) -> Option<&Class> { 42 | let ty = unsafe { (self.vft().get_class)(self, name) }; 43 | unsafe { ty.cast::().as_ref() } 44 | } 45 | 46 | /// Retrieve a type by its name. 47 | #[inline] 48 | pub fn get_type(&self, name: CName) -> Option<&Type> { 49 | let ty = unsafe { (self.vft().get_type)(self, name) }; 50 | unsafe { ty.cast::().as_ref() } 51 | } 52 | 53 | /// Retrieve an enum by its name. 54 | #[inline] 55 | pub fn get_enum(&self, name: CName) -> Option<&Enum> { 56 | let ty = unsafe { (self.vft().get_enum)(self, name) }; 57 | unsafe { ty.cast::().as_ref() } 58 | } 59 | 60 | /// Retrieve a bitfield by its name. 61 | #[inline] 62 | pub fn get_bitfield(&self, name: CName) -> Option<&Bitfield> { 63 | let ty = unsafe { (self.vft().get_bitfield)(self, name) }; 64 | unsafe { ty.cast::().as_ref() } 65 | } 66 | 67 | /// Retrieve a function by its name. 68 | #[inline] 69 | pub fn get_function(&self, name: CName) -> Option<&Function> { 70 | let ty = unsafe { (self.vft().get_function)(self, name) }; 71 | unsafe { ty.cast::().as_ref() } 72 | } 73 | 74 | /// Retrieve all native types and collect them into a [`RedArray`]`. 75 | #[inline] 76 | pub fn get_native_types(&self) -> RedArray<&Type> { 77 | let mut out = RedArray::default(); 78 | unsafe { 79 | (self.vft().get_native_types)(self, &mut out as *mut _ as *mut RedArray<*mut Type>) 80 | }; 81 | out 82 | } 83 | 84 | /// Retrieve all enums and collect them into a [`RedArray`]`. 85 | #[inline] 86 | pub fn get_enums(&self) -> RedArray<&Enum> { 87 | let mut out = RedArray::default(); 88 | unsafe { (self.vft().get_enums)(self, &mut out as *mut _ as *mut RedArray<*mut Enum>) }; 89 | out 90 | } 91 | 92 | /// Retrieve all bitfields and collect them into a [`RedArray`]`. 93 | #[inline] 94 | pub fn get_bitfields(&self, scripted_only: bool) -> RedArray<&Bitfield> { 95 | let mut out = RedArray::default(); 96 | unsafe { 97 | (self.vft().get_bitfields)( 98 | self, 99 | &mut out as *mut _ as *mut RedArray<*mut Bitfield>, 100 | scripted_only, 101 | ) 102 | }; 103 | out 104 | } 105 | 106 | /// Retrieve all global functions and collect them into a [`RedArray`]`. 107 | #[inline] 108 | pub fn get_global_functions(&self) -> RedArray<&Function> { 109 | let mut out = RedArray::default(); 110 | unsafe { 111 | (self.vft().get_global_functions)( 112 | self, 113 | &mut out as *mut _ as *mut RedArray<*mut Function>, 114 | ) 115 | }; 116 | out 117 | } 118 | 119 | /// Retrieve all instance methods and collect them into a [`RedArray`]`. 120 | #[inline] 121 | pub fn get_class_functions(&self) -> RedArray<&Function> { 122 | let mut out = RedArray::default(); 123 | unsafe { 124 | (self.vft().get_class_functions)( 125 | self, 126 | &mut out as *mut _ as *mut RedArray<*mut Function>, 127 | ) 128 | }; 129 | out 130 | } 131 | 132 | /// Retrieve base class and its inheritors, optionally including abstract classes. 133 | #[inline] 134 | pub fn get_classes(&self, base: &Class, include_abstract: bool) -> RedArray<&Class> { 135 | let mut out = RedArray::default(); 136 | unsafe { 137 | (self.vft().get_classes)( 138 | self, 139 | base, 140 | &mut out as *mut _ as *mut RedArray<*mut Class>, 141 | None, 142 | include_abstract, 143 | ) 144 | }; 145 | out 146 | } 147 | 148 | /// Retrieve derived classes, omitting base in the output. 149 | #[inline] 150 | pub fn get_derived_classes(&self, base: &Class) -> RedArray<&Class> { 151 | let mut out = RedArray::default(); 152 | unsafe { 153 | (self.vft().get_derived_classes)( 154 | self, 155 | base, 156 | &mut out as *mut _ as *mut RedArray<*mut Class>, 157 | ) 158 | }; 159 | out 160 | } 161 | 162 | /// Retrieve a class by its script name. 163 | #[inline] 164 | pub fn get_class_by_script_name(&self, name: CName) -> Option<&Class> { 165 | let ty = unsafe { (self.vft().get_class_by_script_name)(self, name) }; 166 | unsafe { ty.cast::().as_ref() } 167 | } 168 | 169 | /// Retrieve an enum by its script name. 170 | #[inline] 171 | pub fn get_enum_by_script_name(&self, name: CName) -> Option<&Enum> { 172 | let ty = unsafe { (self.vft().get_enum_by_script_name)(self, name) }; 173 | unsafe { ty.cast::().as_ref() } 174 | } 175 | 176 | /// Retrieve a reference to a map of all types by name. 177 | #[inline] 178 | pub fn type_map(&self) -> &RedHashMap { 179 | unsafe { &*(&self.0.types as *const _ as *const RedHashMap) } 180 | } 181 | 182 | /// Retrieve a reference to a map of all script to native name aliases. 183 | #[inline] 184 | pub fn script_to_native_map(&self) -> &RedHashMap { 185 | unsafe { &*(&self.0.scriptToNative as *const _ as *const RedHashMap) } 186 | } 187 | 188 | /// Retrieve a reference to a map of all native to script name aliases. 189 | #[inline] 190 | pub fn native_to_script_map(&self) -> &RedHashMap { 191 | unsafe { &*(&self.0.nativeToScript as *const _ as *const RedHashMap) } 192 | } 193 | 194 | /// Resolves a static method by its full name, which should be in the format `Class::Method`. 195 | #[inline] 196 | pub fn resolve_static_method_by_full_name(&self, full_name: &str) -> Option<&Function> { 197 | fn resolve_native(rtti: &RttiSystem, class: CName, method: CName) -> Option<&Function> { 198 | rtti.get_class(class)? 199 | .static_methods() 200 | .iter() 201 | .find(|m| m.as_function().name() == method) 202 | .map(|m| m.as_function()) 203 | } 204 | 205 | // split on bytes rather than str to avoid inefficient UTF-8 scanning LLVM fails to 206 | // optimize away 207 | let mut parts = full_name.as_bytes().split(|&c| c == b':'); 208 | let class = CName::from_bytes(parts.next()?); 209 | parts.next()?; // skip the separator 210 | let method = CName::from_bytes(parts.next()?); 211 | 212 | self.get_function(CName::new(full_name)) 213 | .or_else(|| resolve_native(self, class, method)) 214 | } 215 | 216 | /// Resolve the context required for a call to a static scripted method on specified class. 217 | /// Returns `None` if the class was not found in the RTTI system. 218 | pub fn resolve_static_context(&self, class: CName) -> Option> { 219 | let game = GameEngine::get().game_instance(); 220 | let get_context = |class| Some(game.get_system(self.get_class(class)?.as_type())); 221 | let ctx = get_context(class)?; 222 | if ctx.is_null() { 223 | get_context(CName::new("cpPlayerSystem")) 224 | } else { 225 | Some(ctx) 226 | } 227 | } 228 | 229 | #[inline] 230 | fn vft(&self) -> &RttiSystemVft { 231 | unsafe { &*(self.0._base.vtable_ as *const RttiSystemVft) } 232 | } 233 | } 234 | 235 | /// The RTTI system containing information about all types in the game. 236 | /// This variant allows for modifying the RTTI system and locks it for exclusive access. 237 | #[repr(transparent)] 238 | pub struct RttiSystemMut(red::CRTTISystem); 239 | 240 | impl RttiSystemMut { 241 | /// Acquire a write lock on the RTTI system. You should be careful not to hold the lock for 242 | /// too long, because interleaving reads and write operations can lead to deadlocks. 243 | #[inline] 244 | pub fn get() -> RwSpinLockWriteGuard<'static, Self> { 245 | unsafe { 246 | let rtti = red::CRTTISystem_Get(); 247 | let lock = &(*rtti).typesLock; 248 | RwSpinLockWriteGuard::new(lock, ptr::NonNull::new_unchecked(rtti as _)) 249 | } 250 | } 251 | 252 | /// Retrieve a mutable reference to a class by its name 253 | pub fn get_class(&mut self, name: CName) -> Option<&mut Class> { 254 | // implemented manually to avoid the game trying to obtain the type lock 255 | let (types, types_by_id, type_ids) = self.split_types(); 256 | if let Some(ty) = types.get_mut(&name) { 257 | return ty.as_class_mut(); 258 | } 259 | let &id = type_ids.get(&name)?; 260 | types_by_id.get_mut(&id)?.as_class_mut() 261 | } 262 | 263 | /// Register a new [`ClassHandle`] with the RTTI system. 264 | /// The handle can be obtained from 265 | /// [`NativeClass::new_handle`](crate::types::NativeClass::new_handle). 266 | pub fn register_class(&mut self, mut class: ClassHandle) { 267 | // implemented manually to avoid the game trying to obtain the type lock 268 | let id = unsafe { red::RTTIRegistrator::GetNextId() }; 269 | self.type_map() 270 | .insert(class.as_ref().name(), class.as_mut().as_type_mut()); 271 | self.type_by_id_map() 272 | .insert(id, class.as_mut().as_type_mut()); 273 | self.type_id_map().insert(class.as_ref().name(), id); 274 | } 275 | 276 | /// Register a new [`GlobalFunction`] with the RTTI system. 277 | /// The function can be obtained from [`GlobalFunction::new`]. 278 | #[inline] 279 | pub fn register_function(&mut self, function: PoolRef) { 280 | unsafe { (self.vft().register_function)(self, &*function) } 281 | // RTTI takes ownership of it from now on 282 | mem::forget(function); 283 | } 284 | 285 | #[inline] 286 | fn type_map(&mut self) -> &mut RedHashMap { 287 | unsafe { &mut *(&mut self.0.types as *mut _ as *mut RedHashMap) } 288 | } 289 | 290 | #[inline] 291 | fn type_by_id_map(&mut self) -> &mut RedHashMap { 292 | unsafe { &mut *(&mut self.0.typesByAsyncId as *mut _ as *mut RedHashMap) } 293 | } 294 | 295 | #[inline] 296 | fn type_id_map(&mut self) -> &mut RedHashMap { 297 | unsafe { &mut *(&mut self.0.typeAsyncIds as *mut _ as *mut RedHashMap) } 298 | } 299 | 300 | #[inline] 301 | #[allow(clippy::type_complexity)] 302 | fn split_types( 303 | &mut self, 304 | ) -> ( 305 | &mut RedHashMap, 306 | &mut RedHashMap, 307 | &mut RedHashMap, 308 | ) { 309 | unsafe { 310 | ( 311 | &mut *(&mut self.0.types as *mut _ as *mut RedHashMap), 312 | &mut *(&mut self.0.typesByAsyncId as *mut _ as *mut RedHashMap), 313 | &mut *(&mut self.0.typeAsyncIds as *mut _ as *mut RedHashMap), 314 | ) 315 | } 316 | } 317 | 318 | #[inline] 319 | fn vft(&self) -> &RttiSystemVft { 320 | unsafe { &*(self.0._base.vtable_ as *const RttiSystemVft) } 321 | } 322 | } 323 | 324 | #[repr(C)] 325 | struct RttiSystemVft { 326 | get_type: unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Type, 327 | get_type_by_async_id: 328 | unsafe extern "fastcall" fn(this: *const RttiSystem, async_id: u32) -> *mut Type, 329 | get_class: unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Class, 330 | get_enum: unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Enum, 331 | get_bitfield: 332 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Bitfield, 333 | _sub_28: unsafe extern "fastcall" fn(this: *const RttiSystem), 334 | get_function: 335 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *mut Function, 336 | _sub_38: unsafe extern "fastcall" fn(this: *const RttiSystem), 337 | get_native_types: 338 | unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Type>), 339 | get_global_functions: 340 | unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Function>), 341 | _sub_50: unsafe extern "fastcall" fn(this: *const RttiSystem), 342 | get_class_functions: 343 | unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Function>), 344 | get_enums: unsafe extern "fastcall" fn(this: *const RttiSystem, out: *mut RedArray<*mut Enum>), 345 | get_bitfields: unsafe extern "fastcall" fn( 346 | this: *const RttiSystem, 347 | out: *mut RedArray<*mut Bitfield>, 348 | scripted_only: bool, 349 | ), 350 | get_classes: unsafe extern "fastcall" fn( 351 | this: *const RttiSystem, 352 | base_class: *const Class, 353 | out: *mut RedArray<*mut Class>, 354 | filter: Option bool>, 355 | include_abstract: bool, 356 | ), 357 | get_derived_classes: unsafe extern "fastcall" fn( 358 | this: *const RttiSystem, 359 | base_class: *const Class, 360 | out: *mut RedArray<*mut Class>, 361 | ), 362 | register_type: unsafe extern "fastcall" fn(this: *mut RttiSystem, ty: *mut Type, async_id: u32), 363 | _sub_88: unsafe extern "fastcall" fn(this: *const RttiSystem), 364 | _sub_90: unsafe extern "fastcall" fn(this: *const RttiSystem), 365 | unregister_type: unsafe extern "fastcall" fn(this: *mut RttiSystem, ty: *mut Type), 366 | register_function: 367 | unsafe extern "fastcall" fn(this: *const RttiSystemMut, function: *const GlobalFunction), 368 | unregister_function: 369 | unsafe extern "fastcall" fn(this: *const RttiSystem, function: *const GlobalFunction), 370 | _sub_b0: unsafe extern "fastcall" fn(this: *const RttiSystem), 371 | _sub_b8: unsafe extern "fastcall" fn(this: *const RttiSystem), 372 | // FIXME: crashes when used, signature is probably wrong 373 | _add_register_callback: unsafe extern "fastcall" fn( 374 | this: *const RttiSystem, 375 | function: unsafe extern "C" fn() -> (), 376 | ), 377 | // FIXME: crashes when used, signature is probably wrong 378 | _add_post_register_callback: unsafe extern "fastcall" fn( 379 | this: *const RttiSystem, 380 | function: unsafe extern "C" fn() -> (), 381 | ), 382 | _sub_d0: unsafe extern "fastcall" fn(this: *const RttiSystem), 383 | _sub_d8: unsafe extern "fastcall" fn(this: *const RttiSystem), 384 | _create_scripted_class: unsafe extern "fastcall" fn( 385 | this: *mut RttiSystem, 386 | name: CName, 387 | flags: ClassFlags, 388 | parent: *const Class, 389 | ), 390 | // FIXME: signature is wrong, but how to represent name and value of enumerator ? 391 | // https://github.com/WopsS/RED4ext.SDK/blob/124984353556f7b343041b810040062fbaa96196/include/RED4ext/RTTISystem.hpp#L50 392 | _create_scripted_enum: unsafe extern "fastcall" fn( 393 | this: *const RttiSystem, 394 | name: CName, 395 | size: i8, 396 | variants: *mut RedArray, 397 | ), 398 | // FIXME: signature is wrong, but how to represent name and bit ? 399 | // https://github.com/WopsS/RED4ext.SDK/blob/124984353556f7b343041b810040062fbaa96196/include/RED4ext/RTTISystem.hpp#L54 400 | _create_scripted_bitfield: 401 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName, bits: *mut RedArray), 402 | _initialize_script_runtime: unsafe extern "fastcall" fn(this: *const RttiSystem), 403 | register_script_name: unsafe extern "fastcall" fn( 404 | this: *const RttiSystem, 405 | native_name: CName, 406 | script_name: CName, 407 | ), 408 | get_class_by_script_name: 409 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *const Class, 410 | get_enum_by_script_name: 411 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: CName) -> *const Enum, 412 | // FIXME: crashes when used, signature is probably wrong 413 | _convert_native_to_script_name: 414 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: red::CName) -> red::CName, 415 | // FIXME: crashes when used, signature is probably wrong 416 | _convert_script_to_native_name: 417 | unsafe extern "fastcall" fn(this: *const RttiSystem, name: red::CName) -> red::CName, 418 | } 419 | 420 | /// A helper struct to set up RTTI registration callbacks. 421 | #[derive(Debug)] 422 | pub struct RttiRegistrator; 423 | 424 | impl RttiRegistrator { 425 | /// Add a new RTTI registration callback. 426 | pub fn add( 427 | register: Option, 428 | post_register: Option, 429 | ) { 430 | unsafe { red::RTTIRegistrator::Add(register, post_register, false) }; 431 | } 432 | } 433 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | mod opt; 2 | pub use opt::Opt; 3 | mod cruid; 4 | pub use cruid::Cruid; 5 | mod engine_time; 6 | pub use engine_time::EngineTime; 7 | mod entity_id; 8 | pub use entity_id::EntityId; 9 | mod game_time; 10 | pub use game_time::GameTime; 11 | mod item_id; 12 | pub use item_id::{GameEItemIdFlag, GamedataItemStructure, ItemId}; 13 | mod res; 14 | pub use res::{RaRef, ResRef}; 15 | mod tweak_db_id; 16 | pub use tweak_db_id::TweakDbId; 17 | pub mod array; 18 | pub use array::RedArray; 19 | mod refs; 20 | pub use refs::{Ref, ScriptRef, WeakRef}; 21 | mod string; 22 | pub use string::RedString; 23 | mod cname; 24 | pub use cname::{CName, CNamePool}; 25 | mod rtti; 26 | pub use rtti::{ 27 | ArrayType, Bitfield, Class, ClassFlags, ClassHandle, CurveType, Enum, Function, FunctionFlags, 28 | FunctionHandler, GlobalFunction, IScriptable, ISerializable, Method, NativeArrayType, 29 | NativeClass, PointerType, Property, PropertyFlags, RaRefType, RefType, ResourceRefType, 30 | ScriptRefType, StaticArrayType, StaticMethod, TaggedType, Type, TypeKind, ValueContainer, 31 | ValuePtr, WeakRefType, 32 | }; 33 | mod bytecode; 34 | pub use bytecode::{ 35 | CALL_INSTR_SIZE, Instr, InvokeStatic, InvokeVirtual, OPCODE_SIZE, OpcodeHandler, 36 | }; 37 | mod stack; 38 | pub use stack::{StackArg, StackFrame}; 39 | mod allocator; 40 | pub use allocator::{IAllocator, PoolRef, Poolable, PoolableOps}; 41 | mod hash; 42 | pub use hash::{Hash, RedHashMap}; 43 | mod sync; 44 | pub use sync::{RwSpinLockReadGuard, RwSpinLockWriteGuard}; 45 | mod game_engine; 46 | pub use game_engine::{GameEngine, GameInstance, NativeGameInstance, ScriptableSystem}; 47 | mod misc; 48 | pub use misc::{ 49 | Curve, DataBuffer, DateTime, DeferredDataBuffer, EditorObjectId, Guid, LocalizationString, 50 | MessageResourcePath, MultiChannelCurve, NodeRef, ResourceRef, SharedDataBuffer, StaticArray, 51 | Variant, 52 | }; 53 | -------------------------------------------------------------------------------- /src/types/allocator.rs: -------------------------------------------------------------------------------- 1 | use std::num::NonZeroUsize; 2 | use std::{mem, ops, ptr}; 3 | 4 | use once_cell::race::OnceNonZeroUsize; 5 | use sealed::sealed; 6 | 7 | use super::{GlobalFunction, IScriptable, Method, Property, StaticMethod}; 8 | use crate::raw::root::RED4ext as red; 9 | use crate::raw::root::RED4ext::Memory::AllocationResult; 10 | use crate::{VoidPtr, fnv1a32}; 11 | 12 | /// An interface for allocating and freeing memory. 13 | #[derive(Debug)] 14 | #[repr(transparent)] 15 | pub struct IAllocator(red::Memory::IAllocator); 16 | 17 | impl IAllocator { 18 | /// Frees the memory pointed by `memory`. 19 | #[inline] 20 | pub unsafe fn free(&self, memory: *mut T) { 21 | let mut alloc = AllocationResult { 22 | memory: memory as VoidPtr, 23 | size: 0, 24 | }; 25 | unsafe { 26 | ((*self.0.vtable_).IAllocator_Free)( 27 | &self.0 as *const _ as *mut red::Memory::IAllocator, 28 | &mut alloc, 29 | ) 30 | } 31 | } 32 | 33 | /// Allocates `size` bytes of memory with `alignment` bytes alignment. 34 | #[inline] 35 | pub unsafe fn alloc_aligned(&self, size: u32, alignment: u32) -> *mut T { 36 | unsafe { 37 | let result = ((*self.0.vtable_).IAllocator_GetHandle)( 38 | &self.0 as *const _ as *mut red::Memory::IAllocator, 39 | ); 40 | let vault = vault_get(result); 41 | vault_alloc_aligned(vault, size, alignment).unwrap_or(ptr::null_mut()) as _ 42 | } 43 | } 44 | } 45 | 46 | /// A reference to a value stored in a pool. 47 | #[derive(Debug)] 48 | pub struct PoolRef(*mut T); 49 | 50 | impl PoolRef> { 51 | #[inline] 52 | pub(super) unsafe fn assume_init(self) -> PoolRef { 53 | let res = PoolRef(self.0 as *mut T); 54 | mem::forget(self); 55 | res 56 | } 57 | } 58 | 59 | impl ops::Deref for PoolRef { 60 | type Target = T; 61 | 62 | #[inline] 63 | fn deref(&self) -> &Self::Target { 64 | unsafe { &*self.0 } 65 | } 66 | } 67 | 68 | impl ops::DerefMut for PoolRef { 69 | #[inline] 70 | fn deref_mut(&mut self) -> &mut Self::Target { 71 | unsafe { &mut *self.0 } 72 | } 73 | } 74 | 75 | impl Drop for PoolRef { 76 | #[inline] 77 | fn drop(&mut self) { 78 | unsafe { ptr::drop_in_place(self.0) }; 79 | T::free(self); 80 | } 81 | } 82 | 83 | /// A trait for types that can be stored in a pool. 84 | #[sealed] 85 | pub trait Poolable { 86 | type Pool: Pool; 87 | } 88 | 89 | #[sealed] 90 | impl Poolable for GlobalFunction { 91 | type Pool = FunctionPool; 92 | } 93 | 94 | #[sealed] 95 | impl Poolable for Method { 96 | type Pool = FunctionPool; 97 | } 98 | 99 | #[sealed] 100 | impl Poolable for StaticMethod { 101 | type Pool = FunctionPool; 102 | } 103 | 104 | #[sealed] 105 | impl Poolable for Property { 106 | type Pool = PropertyPool; 107 | } 108 | 109 | #[sealed] 110 | impl Poolable for IScriptable { 111 | type Pool = ScriptPool; 112 | } 113 | 114 | #[sealed] 115 | impl Poolable for mem::MaybeUninit 116 | where 117 | T: Poolable, 118 | { 119 | type Pool = T::Pool; 120 | } 121 | 122 | /// A trait with operations for types that can be stored in a pool. 123 | #[sealed] 124 | pub trait PoolableOps: Poolable + Sized { 125 | /// Allocates memory for `Self`. The resulting value must be initialized before use. 126 | fn alloc() -> Option>>; 127 | /// Frees memory pointed by `ptr`. 128 | fn free(ptr: &mut PoolRef); 129 | } 130 | 131 | #[sealed] 132 | impl PoolableOps for T { 133 | fn alloc() -> Option>> { 134 | let result = unsafe { vault_alloc(T::Pool::vault(), mem::size_of::() as u32)? }; 135 | (!result.is_null()).then(|| PoolRef(result.cast::>())) 136 | } 137 | 138 | fn free(ptr: &mut PoolRef) { 139 | let mut alloc = AllocationResult { 140 | memory: ptr.0 as VoidPtr, 141 | size: 0, 142 | }; 143 | unsafe { 144 | let free = crate::fn_from_hash!( 145 | Memory_Vault_Free, 146 | unsafe extern "C" fn(*mut red::Memory::Vault, *mut AllocationResult) 147 | ); 148 | free(T::Pool::vault(), &mut alloc); 149 | }; 150 | } 151 | } 152 | 153 | /// A trait for different types of pools. 154 | #[sealed] 155 | pub trait Pool { 156 | const NAME: &'static str; 157 | 158 | fn vault() -> *mut red::Memory::Vault { 159 | static VAULT: OnceNonZeroUsize = OnceNonZeroUsize::new(); 160 | VAULT 161 | .get_or_try_init(|| { 162 | NonZeroUsize::new(unsafe { vault_get(fnv1a32(Self::NAME)) as _ }).ok_or(()) 163 | }) 164 | .expect("should resolve vault") 165 | .get() as _ 166 | } 167 | } 168 | 169 | /// A pool for functions. 170 | #[derive(Debug)] 171 | pub struct FunctionPool; 172 | 173 | #[sealed] 174 | impl Pool for FunctionPool { 175 | const NAME: &'static str = "PoolRTTIFunction"; 176 | } 177 | 178 | /// A pool for properties. 179 | #[derive(Debug)] 180 | pub struct PropertyPool; 181 | 182 | #[sealed] 183 | impl Pool for PropertyPool { 184 | const NAME: &'static str = "PoolRTTIProperty"; 185 | } 186 | 187 | /// A pool for RTTI. 188 | #[derive(Debug)] 189 | pub struct RttiPool; 190 | 191 | #[sealed] 192 | impl Pool for RttiPool { 193 | const NAME: &'static str = "PoolRTTI"; 194 | } 195 | 196 | /// A pool for scripts values. 197 | #[derive(Debug)] 198 | pub struct ScriptPool; 199 | 200 | #[sealed] 201 | impl Pool for ScriptPool { 202 | const NAME: &'static str = "PoolScript"; 203 | } 204 | 205 | pub(super) unsafe fn vault_alloc(vault: *mut red::Memory::Vault, size: u32) -> Option { 206 | let mut result = AllocationResult::default(); 207 | unsafe { 208 | let alloc = crate::fn_from_hash!( 209 | Memory_Vault_Alloc, 210 | unsafe extern "C" fn(*mut red::Memory::Vault, *mut AllocationResult, u32) 211 | ); 212 | alloc(vault, &mut result, size as _); 213 | }; 214 | (!result.memory.is_null()).then_some(result.memory) 215 | } 216 | 217 | pub(super) unsafe fn vault_alloc_aligned( 218 | vault: *mut red::Memory::Vault, 219 | size: u32, 220 | alignment: u32, 221 | ) -> Option { 222 | let mut result = AllocationResult::default(); 223 | unsafe { 224 | let alloc_aligned = crate::fn_from_hash!( 225 | Memory_Vault_AllocAligned, 226 | unsafe extern "C" fn(*mut red::Memory::Vault, *mut AllocationResult, u32, u32) 227 | ); 228 | alloc_aligned(vault, &mut result, size as _, alignment as _); 229 | }; 230 | (!result.memory.is_null()).then_some(result.memory) 231 | } 232 | 233 | #[cold] 234 | pub(super) unsafe fn vault_get(handle: u32) -> *mut red::Memory::Vault { 235 | unsafe { 236 | let vault = &mut *red::Memory::Vault::Get(); 237 | 238 | vault.poolRegistry.nodesLock.lock_shared(); 239 | let Some(info) = vault 240 | .poolRegistry 241 | .nodes 242 | .iter() 243 | .find(|node| node.handle == handle) 244 | else { 245 | return ptr::null_mut(); 246 | }; 247 | let storage = (*info.storage).allocatorStorage & !7; 248 | vault.poolRegistry.nodesLock.unlock_shared(); 249 | 250 | storage as _ 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /src/types/array.rs: -------------------------------------------------------------------------------- 1 | //! A dynamically sized array. 2 | use std::iter::FusedIterator; 3 | use std::marker::PhantomData; 4 | use std::{fmt, mem, ops, ptr, slice}; 5 | 6 | use super::IAllocator; 7 | use crate::VoidPtr; 8 | use crate::raw::root::RED4ext as red; 9 | 10 | /// A dynamically sized array. 11 | #[repr(transparent)] 12 | pub struct RedArray(red::DynArray); 13 | 14 | impl RedArray { 15 | /// Creates a new empty [`RedArray`]. 16 | #[inline] 17 | pub const fn new() -> Self { 18 | Self(red::DynArray { 19 | entries: ptr::null_mut(), 20 | size: 0, 21 | capacity: 0, 22 | _phantom_0: PhantomData, 23 | }) 24 | } 25 | 26 | /// Creates a new empty [`RedArray`] with the specified capacity. 27 | #[inline] 28 | pub fn with_capacity(capacity: u32) -> Self { 29 | let mut this = Self::new(); 30 | this.realloc(capacity); 31 | this 32 | } 33 | 34 | /// Returns the number of elements in the array. 35 | #[inline] 36 | pub fn len(&self) -> u32 { 37 | self.0.size 38 | } 39 | 40 | /// Returns `true` if the array contains no elements. 41 | #[inline] 42 | pub fn is_empty(&self) -> bool { 43 | self.len() == 0 44 | } 45 | 46 | /// Returns the number of elements the array can hold without reallocating. 47 | #[inline] 48 | pub fn capacity(&self) -> u32 { 49 | self.0.capacity 50 | } 51 | 52 | /// Clears the array, removing all values. 53 | #[inline] 54 | pub fn clear(&mut self) { 55 | let elems: *mut [T] = &mut **self; 56 | unsafe { ptr::drop_in_place(elems) } 57 | self.0.size = 0; 58 | } 59 | 60 | /// Adds an element to the end of the array. 61 | #[inline] 62 | pub fn push(&mut self, value: T) { 63 | let len = self.len(); 64 | self.reserve(1); 65 | unsafe { 66 | ptr::write(self.0.entries.add(len as usize), value); 67 | } 68 | self.0.size = len + 1; 69 | } 70 | 71 | /// Reserve capacity for at least `additional` more elements to be inserted. 72 | pub fn reserve(&mut self, additional: u32) { 73 | let expected = self.len() + additional; 74 | if expected <= self.capacity() { 75 | return; 76 | } 77 | self.realloc(expected.max(self.capacity() + self.capacity() / 2)); 78 | } 79 | 80 | /// Returns an iterator over the elements of the array. 81 | pub fn iter(&self) -> slice::Iter<'_, T> { 82 | self.into_iter() 83 | } 84 | 85 | fn realloc(&mut self, cap: u32) { 86 | let size = mem::size_of::(); 87 | let align = mem::align_of::().max(8); 88 | unsafe { 89 | let realloc = crate::fn_from_hash!( 90 | DynArray_Realloc, 91 | unsafe extern "C" fn(VoidPtr, u32, u32, u32, usize) 92 | ); 93 | realloc(self as *mut _ as VoidPtr, cap, size as u32, align as u32, 0); 94 | }; 95 | } 96 | } 97 | 98 | impl fmt::Debug for RedArray { 99 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 100 | f.debug_list().entries(self.iter()).finish() 101 | } 102 | } 103 | 104 | impl Default for RedArray { 105 | fn default() -> Self { 106 | Self(Default::default()) 107 | } 108 | } 109 | 110 | impl ops::Deref for RedArray { 111 | type Target = [T]; 112 | 113 | #[inline] 114 | fn deref(&self) -> &[T] { 115 | (!self.0.entries.is_null()) 116 | .then(|| unsafe { slice::from_raw_parts(self.0.entries, self.len() as _) }) 117 | .unwrap_or_default() 118 | } 119 | } 120 | 121 | impl ops::DerefMut for RedArray { 122 | #[inline] 123 | fn deref_mut(&mut self) -> &mut [T] { 124 | (!self.0.entries.is_null()) 125 | .then(|| unsafe { slice::from_raw_parts_mut(self.0.entries, self.len() as _) }) 126 | .unwrap_or_default() 127 | } 128 | } 129 | 130 | impl AsRef<[T]> for RedArray { 131 | #[inline] 132 | fn as_ref(&self) -> &[T] { 133 | self 134 | } 135 | } 136 | 137 | impl AsMut<[T]> for RedArray { 138 | #[inline] 139 | fn as_mut(&mut self) -> &mut [T] { 140 | self 141 | } 142 | } 143 | 144 | impl<'a, T> IntoIterator for &'a RedArray { 145 | type IntoIter = slice::Iter<'a, T>; 146 | type Item = &'a T; 147 | 148 | #[inline] 149 | fn into_iter(self) -> Self::IntoIter { 150 | <[T]>::iter(self) 151 | } 152 | } 153 | 154 | impl IntoIterator for RedArray { 155 | type IntoIter = IntoIter; 156 | type Item = T; 157 | 158 | #[inline] 159 | fn into_iter(self) -> Self::IntoIter { 160 | let me = mem::ManuallyDrop::new(self); 161 | IntoIter { 162 | array: red::DynArray { 163 | entries: me.0.entries, 164 | size: me.len(), 165 | capacity: me.capacity(), 166 | ..Default::default() 167 | }, 168 | ptr: me.0.entries, 169 | end: unsafe { me.0.entries.add(me.len() as _) }, 170 | } 171 | } 172 | } 173 | 174 | impl FromIterator for RedArray { 175 | #[inline] 176 | fn from_iter>(iter: I) -> Self { 177 | let mut array = Self::new(); 178 | array.extend(iter); 179 | array 180 | } 181 | } 182 | 183 | impl Extend for RedArray { 184 | fn extend>(&mut self, iter: I) { 185 | let iter = iter.into_iter(); 186 | let (lower, _) = iter.size_hint(); 187 | self.reserve(lower as u32); 188 | for item in iter { 189 | self.push(item); 190 | } 191 | } 192 | } 193 | 194 | impl Drop for RedArray { 195 | #[inline] 196 | fn drop(&mut self) { 197 | if self.capacity() == 0 { 198 | return; 199 | } 200 | let elems: *mut [T] = &mut **self; 201 | unsafe { 202 | ptr::drop_in_place(elems); 203 | (*get_allocator(&self.0)).free(self.0.entries); 204 | }; 205 | } 206 | } 207 | 208 | #[derive(Debug)] 209 | pub struct IntoIter { 210 | array: red::DynArray, 211 | ptr: *mut T, 212 | end: *mut T, 213 | } 214 | 215 | impl Iterator for IntoIter { 216 | type Item = T; 217 | 218 | #[inline] 219 | fn next(&mut self) -> Option { 220 | if self.ptr == self.end { 221 | None 222 | } else { 223 | let old = self.ptr; 224 | self.ptr = unsafe { old.add(1) }; 225 | Some(unsafe { ptr::read(old) }) 226 | } 227 | } 228 | 229 | #[inline] 230 | fn size_hint(&self) -> (usize, Option) { 231 | let len = unsafe { self.end.offset_from(self.ptr) } as usize; 232 | (len, Some(len)) 233 | } 234 | } 235 | 236 | impl DoubleEndedIterator for IntoIter { 237 | #[inline] 238 | fn next_back(&mut self) -> Option { 239 | if self.ptr == self.end { 240 | None 241 | } else { 242 | self.end = unsafe { self.end.sub(1) }; 243 | Some(unsafe { ptr::read(self.end) }) 244 | } 245 | } 246 | } 247 | 248 | impl ExactSizeIterator for IntoIter {} 249 | 250 | impl FusedIterator for IntoIter {} 251 | 252 | impl Drop for IntoIter { 253 | #[inline] 254 | fn drop(&mut self) { 255 | if self.array.capacity == 0 { 256 | return; 257 | } 258 | unsafe { 259 | let elems = slice::from_raw_parts_mut(self.ptr, self.len()); 260 | ptr::drop_in_place(elems); 261 | (*get_allocator(&self.array)).free(self.array.entries); 262 | }; 263 | } 264 | } 265 | 266 | fn get_allocator(arr: &red::DynArray) -> *mut IAllocator { 267 | if arr.capacity == 0 { 268 | &arr.entries as *const _ as *mut _ 269 | } else { 270 | let end = unsafe { arr.entries.add(arr.capacity as _) } as usize; 271 | let aligned = end.next_multiple_of(mem::size_of::()); 272 | aligned as _ 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /src/types/bytecode.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | use sealed::sealed; 4 | 5 | use super::{CName, Function, IScriptable, StackFrame}; 6 | use crate::VoidPtr; 7 | 8 | pub const OPCODE_SIZE: isize = 1; 9 | pub const CALL_INSTR_SIZE: isize = mem::size_of::() as isize; 10 | 11 | /// A function pointer type for bytecode opcode handlers. 12 | pub type OpcodeHandler = unsafe extern "C" fn(Option<&IScriptable>, &StackFrame, VoidPtr, VoidPtr); 13 | 14 | /// A trait for types that correspond to bytecode instructions. 15 | #[sealed] 16 | pub trait Instr { 17 | const OPCODE: u8; 18 | } 19 | 20 | #[derive(Debug)] 21 | #[repr(C, packed)] 22 | pub struct InvokeStatic { 23 | pub skip: u16, 24 | pub line: u16, 25 | pub func: *mut Function, 26 | pub flags: u16, 27 | } 28 | 29 | #[sealed] 30 | impl Instr for InvokeStatic { 31 | const OPCODE: u8 = 36; 32 | } 33 | 34 | #[derive(Debug)] 35 | #[repr(C, packed)] 36 | pub struct InvokeVirtual { 37 | pub skip: u16, 38 | pub line: u16, 39 | pub name: CName, 40 | pub flags: u16, 41 | } 42 | 43 | #[sealed] 44 | impl Instr for InvokeVirtual { 45 | const OPCODE: u8 = 37; 46 | } 47 | -------------------------------------------------------------------------------- /src/types/cname.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{self, CStr}; 2 | use std::fmt; 3 | use std::hash::Hash; 4 | 5 | use crate::fnv1a64; 6 | use crate::raw::root::RED4ext as red; 7 | 8 | /// A hash representing an immutable string stored in a global name pool. 9 | #[derive(Debug, Default, Clone, Copy)] 10 | #[repr(transparent)] 11 | pub struct CName(red::CName); 12 | 13 | impl CName { 14 | /// Creates a new `CName` from the given string. 15 | /// This function just calculates the hash of the string using the FNV-1a algorithm. 16 | /// If you want it to be added to the global name pool, use [`CNamePool::add_cstr`]. 17 | #[inline] 18 | pub const fn new(name: &str) -> Self { 19 | Self::from_bytes(name.as_bytes()) 20 | } 21 | 22 | pub const fn from_bytes(name: &[u8]) -> Self { 23 | #[allow(clippy::equatable_if_let)] 24 | if let b"None" = name { 25 | return Self::undefined(); 26 | } 27 | Self(red::CName { 28 | hash: fnv1a64(name), 29 | }) 30 | } 31 | 32 | /// Returns a [`CName`] representing an undefined name. 33 | #[inline] 34 | pub const fn undefined() -> Self { 35 | Self(red::CName { hash: 0 }) 36 | } 37 | 38 | pub(super) fn from_raw(raw: red::CName) -> Self { 39 | Self(raw) 40 | } 41 | 42 | pub(super) fn to_raw(self) -> red::CName { 43 | self.0 44 | } 45 | 46 | /// Returns the string representation of the [`CName`]. 47 | pub fn as_str(&self) -> &'static str { 48 | unsafe { ffi::CStr::from_ptr(self.0.ToString()) } 49 | .to_str() 50 | .unwrap() 51 | } 52 | } 53 | 54 | impl From for CName { 55 | fn from(hash: u64) -> Self { 56 | Self(red::CName { hash }) 57 | } 58 | } 59 | 60 | impl From for u64 { 61 | fn from(CName(red::CName { hash }): CName) -> Self { 62 | hash 63 | } 64 | } 65 | 66 | impl std::fmt::Display for CName { 67 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 68 | write!( 69 | f, 70 | "{}", 71 | if self.0.hash == 0 { 72 | "None" 73 | } else { 74 | self.as_str() 75 | } 76 | ) 77 | } 78 | } 79 | 80 | impl PartialEq for CName { 81 | #[inline] 82 | fn eq(&self, other: &Self) -> bool { 83 | self.0.hash == other.0.hash 84 | } 85 | } 86 | 87 | impl Eq for CName {} 88 | 89 | impl PartialOrd for CName { 90 | #[inline] 91 | fn partial_cmp(&self, other: &Self) -> Option { 92 | Some(self.cmp(other)) 93 | } 94 | } 95 | 96 | impl Ord for CName { 97 | #[inline] 98 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 99 | self.0.hash.cmp(&other.0.hash) 100 | } 101 | } 102 | 103 | impl Hash for CName { 104 | #[inline] 105 | fn hash(&self, state: &mut H) { 106 | self.0.hash.hash(state) 107 | } 108 | } 109 | 110 | /// A global pool containing all [`CName`]s. 111 | #[derive(Debug)] 112 | #[repr(transparent)] 113 | pub struct CNamePool(red::CNamePool); 114 | 115 | impl CNamePool { 116 | pub fn add_cstr(str: &CStr) -> CName { 117 | unsafe { 118 | let add_cstr = crate::fn_from_hash!( 119 | CNamePool_AddCstr, 120 | unsafe extern "C" fn(&mut CName, *const i8) 121 | ); 122 | let mut cname = CName::default(); 123 | add_cstr(&mut cname, str.as_ptr()); 124 | cname 125 | } 126 | } 127 | } 128 | 129 | #[cfg(test)] 130 | mod test { 131 | use super::*; 132 | 133 | #[test] 134 | fn calculate_hashes() { 135 | assert_eq!( 136 | u64::from(CName::new("IScriptable")), 137 | 3_191_163_302_135_919_211 138 | ); 139 | assert_eq!(u64::from(CName::new("Vector2")), 7_466_804_955_052_523_504); 140 | assert_eq!(u64::from(CName::new("Color")), 3_769_135_706_557_701_272); 141 | assert_eq!(u64::from(CName::new("None")), 0); 142 | assert_eq!(u64::from(CName::new("")), 0xCBF2_9CE4_8422_2325); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/types/cruid.rs: -------------------------------------------------------------------------------- 1 | use std::hash::Hash; 2 | 3 | use crate::fnv1a32; 4 | use crate::raw::root::RED4ext as red; 5 | 6 | #[derive(Debug, Clone, Copy)] 7 | #[repr(transparent)] 8 | pub struct Cruid(red::CRUID); 9 | 10 | impl Cruid { 11 | #[inline] 12 | pub const fn is_defined(self) -> bool { 13 | self.0.unk00 != 0 14 | } 15 | 16 | pub const fn new(str: &str) -> Self { 17 | Self(red::CRUID { 18 | // https://discord.com/channels/717692382849663036/717720094196760760/1208391892119719946 19 | unk00: 0xF000_0000_0000_0000_u64 as i64 | (fnv1a32(str) << 2) as i64, 20 | }) 21 | } 22 | } 23 | 24 | impl PartialEq for Cruid { 25 | fn eq(&self, other: &Self) -> bool { 26 | self.0.unk00 == other.0.unk00 27 | } 28 | } 29 | 30 | impl Eq for Cruid {} 31 | 32 | impl PartialOrd for Cruid { 33 | fn partial_cmp(&self, other: &Self) -> Option { 34 | Some(self.cmp(other)) 35 | } 36 | } 37 | 38 | impl Ord for Cruid { 39 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 40 | self.0.unk00.cmp(&other.0.unk00) 41 | } 42 | } 43 | 44 | impl Hash for Cruid { 45 | fn hash(&self, state: &mut H) { 46 | self.0.unk00.hash(state); 47 | } 48 | } 49 | 50 | impl Default for Cruid { 51 | fn default() -> Self { 52 | Self(red::CRUID { unk00: 0 }) 53 | } 54 | } 55 | 56 | impl From for Cruid { 57 | fn from(hash: i64) -> Self { 58 | Self(red::CRUID { unk00: hash }) 59 | } 60 | } 61 | 62 | impl From for i64 { 63 | fn from(Cruid(red::CRUID { unk00 }): Cruid) -> Self { 64 | unk00 65 | } 66 | } 67 | 68 | #[cfg(not(test))] // only available in-game 69 | impl From for Cruid { 70 | fn from(value: crate::types::CName) -> Self { 71 | Self::new(value.as_str()) 72 | } 73 | } 74 | 75 | #[cfg(test)] 76 | mod tests { 77 | use super::Cruid; 78 | use crate::types::CName; 79 | 80 | #[test] 81 | fn conversion() { 82 | const NAME: &str = "Items.FirstAidWhiffV0"; 83 | let cruid = Cruid::new(NAME); 84 | assert_eq!(i64::from(cruid), -0x0FFF_FFFF_CFF0_570C); 85 | let cname = CName::new(NAME); 86 | assert_eq!(u64::from(cname), 0x4856_A96F_939D_54FD); 87 | // CName and CRUID hashes are not equivalent 88 | assert_ne!(i64::from(cruid), u64::from(cname) as i64); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/types/engine_time.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | #[derive(Default, Clone, Copy)] 4 | #[repr(transparent)] 5 | pub struct EngineTime(f64); 6 | 7 | impl EngineTime { 8 | pub fn is_valid(&self) -> bool { 9 | self.0 != 0. 10 | } 11 | 12 | pub fn as_secs_f64(&self) -> f64 { 13 | self.0 14 | } 15 | } 16 | 17 | impl std::ops::AddAssign for EngineTime { 18 | /// # Panics 19 | /// 20 | /// Panics if the sum ends up being `f64::NAN`, `f64::INFINITY` or `f64::NEG_INFINITY`. 21 | fn add_assign(&mut self, rhs: f64) { 22 | let current = self.as_secs_f64(); 23 | let addition = current + rhs; 24 | assert!(!addition.is_infinite(), "EngineTime cannot be infinity"); 25 | assert!(!addition.is_nan(), "EngineTime cannot be NaN"); 26 | self.0 = addition; 27 | } 28 | } 29 | 30 | impl std::ops::Add for EngineTime { 31 | type Output = EngineTime; 32 | 33 | /// # Panics 34 | /// 35 | /// Panics if the sum ends up being `f64::NAN`, `f64::INFINITY` or `f64::NEG_INFINITY`. 36 | fn add(self, rhs: f64) -> Self::Output { 37 | use std::ops::AddAssign; 38 | let mut copy = self; 39 | copy.add_assign(rhs); 40 | copy 41 | } 42 | } 43 | 44 | impl std::ops::SubAssign for EngineTime { 45 | /// # Panics 46 | /// 47 | /// Panics if the sum ends up being `f64::NAN`, `f64::INFINITY` or `f64::NEG_INFINITY`. 48 | fn sub_assign(&mut self, rhs: f64) { 49 | let current = self.as_secs_f64(); 50 | let substraction = current - rhs; 51 | assert!(!substraction.is_infinite(), "EngineTime cannot be infinity"); 52 | assert!(!substraction.is_nan(), "EngineTime cannot be NaN"); 53 | self.0 = substraction; 54 | } 55 | } 56 | 57 | impl std::ops::Sub for EngineTime { 58 | type Output = EngineTime; 59 | 60 | /// # Panics 61 | /// 62 | /// Panics if the sum ends up being `f64::NAN`, `f64::INFINITY` or `f64::NEG_INFINITY`. 63 | fn sub(self, rhs: f64) -> Self::Output { 64 | use std::ops::SubAssign; 65 | let mut copy = self; 66 | copy.sub_assign(rhs); 67 | copy 68 | } 69 | } 70 | 71 | impl PartialEq for EngineTime { 72 | fn eq(&self, other: &Self) -> bool { 73 | self.0.eq(&other.0) 74 | } 75 | } 76 | 77 | impl PartialOrd for EngineTime { 78 | fn partial_cmp(&self, other: &Self) -> Option { 79 | self.0.partial_cmp(&other.0) 80 | } 81 | } 82 | 83 | impl TryFrom for EngineTime { 84 | type Error = EngineTimeError; 85 | 86 | fn try_from(value: f64) -> Result { 87 | if value.is_infinite() { 88 | return Err(EngineTimeError::OutOfBounds); 89 | } 90 | if value.is_nan() { 91 | return Err(EngineTimeError::NotANumber); 92 | } 93 | Ok(Self(value)) 94 | } 95 | } 96 | 97 | impl From for f64 { 98 | fn from(EngineTime(value): EngineTime) -> Self { 99 | value 100 | } 101 | } 102 | 103 | impl TryFrom for EngineTime { 104 | type Error = EngineTimeError; 105 | 106 | fn try_from(value: Duration) -> Result { 107 | let value = value.as_secs_f64(); 108 | value.try_into() 109 | } 110 | } 111 | 112 | impl std::ops::Add for EngineTime { 113 | type Output = Self; 114 | 115 | fn add(self, rhs: Duration) -> Self::Output { 116 | self.add(rhs.as_secs_f64()) 117 | } 118 | } 119 | 120 | impl std::ops::AddAssign for EngineTime { 121 | fn add_assign(&mut self, rhs: Duration) { 122 | self.add_assign(rhs.as_secs_f64()); 123 | } 124 | } 125 | 126 | impl std::ops::Sub for EngineTime { 127 | type Output = Self; 128 | 129 | fn sub(self, rhs: Duration) -> Self::Output { 130 | self.sub(rhs.as_secs_f64()) 131 | } 132 | } 133 | 134 | impl std::ops::SubAssign for EngineTime { 135 | fn sub_assign(&mut self, rhs: Duration) { 136 | self.sub_assign(rhs.as_secs_f64()); 137 | } 138 | } 139 | 140 | #[derive(Debug)] 141 | pub enum EngineTimeError { 142 | OutOfBounds, 143 | NotANumber, 144 | } 145 | 146 | impl std::fmt::Display for EngineTimeError { 147 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 148 | write!( 149 | f, 150 | "{}", 151 | match self { 152 | Self::OutOfBounds => "invalid infinite or negative infinite floating-point", 153 | Self::NotANumber => "invalid NaN", 154 | } 155 | ) 156 | } 157 | } 158 | 159 | impl std::error::Error for EngineTimeError {} 160 | 161 | #[cfg(test)] 162 | mod tests { 163 | use std::time::Duration; 164 | 165 | use super::EngineTime; 166 | 167 | #[test] 168 | fn bounds() { 169 | assert!(EngineTime::try_from(f64::INFINITY).is_err()); 170 | assert!(EngineTime::try_from(f64::NEG_INFINITY).is_err()); 171 | 172 | let before = EngineTime::try_from(f64::MAX).unwrap(); 173 | let after = before + Duration::from_millis(1); 174 | assert_eq!(after.as_secs_f64(), f64::MAX); 175 | 176 | let before = EngineTime::try_from(f64::MIN).unwrap(); 177 | let after = before - Duration::from_millis(1); 178 | assert_eq!(after.as_secs_f64(), f64::MIN); 179 | } 180 | 181 | #[test] 182 | fn math() { 183 | let mut time = EngineTime::try_from(3.2).unwrap(); 184 | time += Duration::from_secs_f64(4.1); 185 | 186 | assert_eq!(time.as_secs_f64(), 7.3); 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/types/entity_id.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | use std::hash::Hash; 3 | 4 | use crate::raw::root::RED4ext as red; 5 | 6 | #[derive(Clone, Copy)] 7 | #[repr(transparent)] 8 | pub struct EntityId(red::ent::EntityID); 9 | 10 | impl EntityId { 11 | #[inline] 12 | pub const fn is_defined(self) -> bool { 13 | self.0.hash != 0 14 | } 15 | 16 | #[inline] 17 | pub const fn is_static(self) -> bool { 18 | self.0.hash != 0 && self.0.hash > red::ent::EntityID_DynamicUpperBound 19 | } 20 | 21 | #[inline] 22 | pub const fn is_dynamic(self) -> bool { 23 | self.0.hash != 0 && self.0.hash <= red::ent::EntityID_DynamicUpperBound 24 | } 25 | 26 | #[inline] 27 | pub const fn is_persistable(self) -> bool { 28 | self.0.hash >= red::ent::EntityID_PersistableLowerBound 29 | && self.0.hash < red::ent::EntityID_PersistableUpperBound 30 | } 31 | 32 | #[inline] 33 | pub const fn is_transient(self) -> bool { 34 | self.0.hash != 0 && !self.is_persistable() 35 | } 36 | } 37 | 38 | impl PartialEq for EntityId { 39 | fn eq(&self, other: &Self) -> bool { 40 | self.0.hash == other.0.hash 41 | } 42 | } 43 | 44 | impl Eq for EntityId {} 45 | 46 | impl PartialOrd for EntityId { 47 | fn partial_cmp(&self, other: &Self) -> Option { 48 | Some(self.cmp(other)) 49 | } 50 | } 51 | 52 | impl Ord for EntityId { 53 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 54 | self.0.hash.cmp(&other.0.hash) 55 | } 56 | } 57 | 58 | impl Hash for EntityId { 59 | fn hash(&self, state: &mut H) { 60 | self.0.hash.hash(state); 61 | } 62 | } 63 | 64 | impl Default for EntityId { 65 | fn default() -> Self { 66 | Self(red::ent::EntityID { hash: 0 }) 67 | } 68 | } 69 | 70 | impl From for EntityId { 71 | fn from(hash: u64) -> Self { 72 | Self(red::ent::EntityID { hash }) 73 | } 74 | } 75 | 76 | impl From for u64 { 77 | fn from(EntityId(red::ent::EntityID { hash }): EntityId) -> Self { 78 | hash 79 | } 80 | } 81 | 82 | impl fmt::Debug for EntityId { 83 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 84 | let mut attrs = f.debug_set(); // transient and persistable are exclusive 85 | if self.is_defined() { 86 | if self.is_dynamic() { 87 | attrs.entry(&"dynamic"); 88 | } else { 89 | attrs.entry(&"static"); 90 | } 91 | if self.is_transient() { 92 | attrs.entry(&"transient"); 93 | } 94 | } 95 | if self.is_persistable() { 96 | attrs.entry(&"persistable"); 97 | } 98 | let flags = attrs.finish(); 99 | f.debug_struct("EntityId") 100 | .field("hash", &self.0.hash) 101 | .field("flags", &flags) 102 | .finish_non_exhaustive() 103 | } 104 | } 105 | 106 | /// A simple entity ID representation. 107 | /// 108 | /// Flags are displayed as: 109 | /// - `P`ersistable 110 | /// - `D`ynamic 111 | /// - `T`ransient 112 | /// - `S`tatic 113 | impl std::fmt::Display for EntityId { 114 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 115 | match (self.is_defined(), self.is_persistable()) { 116 | (true, persistable) => { 117 | write!( 118 | f, 119 | "{} {}", 120 | self.0.hash, 121 | match (persistable, self.is_dynamic(), self.is_transient()) { 122 | (true, true, true) => "(P|D|T)", 123 | (true, true, false) => "(P|D)", 124 | (true, false, true) => "(P|S|T)", 125 | (true, false, false) => "(P|S)", 126 | (false, true, true) => "(D|T)", 127 | (false, true, false) => "(D)", 128 | (false, false, true) => "(S|T)", 129 | (false, false, false) => "(S)", 130 | } 131 | ) 132 | } 133 | (false, false) => write!(f, "undefined"), 134 | (false, true) => write!(f, "undefined (P)"), 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/types/game_engine.rs: -------------------------------------------------------------------------------- 1 | use std::mem; 2 | 3 | use super::{IScriptable, Ref, Type}; 4 | use crate::class::{ScriptClass, class_kind}; 5 | use crate::raw::root::RED4ext as red; 6 | use crate::types::WeakRef; 7 | use crate::{NativeRepr, VoidPtr}; 8 | 9 | /// Scripted game instance. 10 | /// 11 | /// It's worth noting that `GameInstance` is named after Redscript and Lua, 12 | /// but it differs from [RED4ext naming convention](https://github.com/WopsS/RED4ext.SDK/blob/master/include/RED4ext/Scripting/Natives/ScriptGameInstance.hpp). 13 | #[derive(Default)] 14 | #[repr(transparent)] 15 | pub struct GameInstance(red::ScriptGameInstance); 16 | 17 | impl GameInstance { 18 | #[inline] 19 | pub fn new() -> Self { 20 | Self(unsafe { 21 | red::ScriptGameInstance::new(GameEngine::get().game_instance() as *const _ as *mut _) 22 | }) 23 | } 24 | } 25 | 26 | unsafe impl NativeRepr for GameInstance { 27 | const NAME: &'static str = "ScriptGameInstance"; 28 | } 29 | 30 | /// Native game instance. 31 | /// 32 | /// Please note that it differs from Redscript and Lua's `GameInstance`, 33 | /// see [`GameInstance`]. 34 | #[derive(Default)] 35 | #[repr(transparent)] 36 | pub struct NativeGameInstance(red::GameInstance); 37 | 38 | impl NativeGameInstance { 39 | #[inline] 40 | pub fn get_system(&self, ty: &Type) -> Ref { 41 | let instance = unsafe { (self.vft().get_system)(self, ty) }; 42 | if instance.is_null() { 43 | return Ref::default(); 44 | } 45 | let instance: &WeakRef = 46 | unsafe { mem::transmute(&(*instance)._base.ref_) }; 47 | instance.clone().upgrade().unwrap_or_default() 48 | } 49 | 50 | #[inline] 51 | fn vft(&self) -> &GameInstanceVft { 52 | unsafe { &*(self.0.vtable_ as *const GameInstanceVft) } 53 | } 54 | } 55 | 56 | impl Drop for NativeGameInstance { 57 | #[inline] 58 | fn drop(&mut self) { 59 | unsafe { (self.vft().destroy)(self) }; 60 | } 61 | } 62 | 63 | #[repr(C)] 64 | pub struct GameInstanceVft { 65 | destroy: unsafe extern "fastcall" fn(this: *mut NativeGameInstance), 66 | get_system: unsafe extern "fastcall" fn( 67 | this: *const NativeGameInstance, 68 | ty: &Type, 69 | ) -> *mut red::IScriptable, 70 | _unk10: VoidPtr, 71 | _unk18: VoidPtr, 72 | _unk20: VoidPtr, 73 | _unk28: VoidPtr, 74 | _unk30: VoidPtr, 75 | _unk38: VoidPtr, 76 | _unk40: VoidPtr, 77 | _unk48: VoidPtr, 78 | _unk50: VoidPtr, 79 | _unk58: VoidPtr, 80 | _unk60: VoidPtr, 81 | _unk68: VoidPtr, 82 | } 83 | 84 | #[repr(transparent)] 85 | pub struct GameEngine(red::CGameEngine); 86 | 87 | impl GameEngine { 88 | pub fn get<'a>() -> &'a Self { 89 | unsafe { &*(red::CGameEngine::Get() as *const GameEngine) } 90 | } 91 | 92 | pub fn game_instance(&self) -> &NativeGameInstance { 93 | unsafe { &*((*self.0.framework).gameInstance as *const NativeGameInstance) } 94 | } 95 | } 96 | 97 | #[repr(transparent)] 98 | pub struct ScriptableSystem(red::ScriptableSystem); 99 | 100 | unsafe impl ScriptClass for ScriptableSystem { 101 | type Kind = class_kind::Native; 102 | 103 | const NAME: &'static str = "gameScriptableSystem"; 104 | } 105 | 106 | impl AsRef for ScriptableSystem { 107 | fn as_ref(&self) -> &IScriptable { 108 | unsafe { mem::transmute(&self.0._base._base) } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/types/game_time.rs: -------------------------------------------------------------------------------- 1 | use std::hash::Hash; 2 | 3 | use crate::raw::root::RED4ext as red; 4 | 5 | #[derive(Default, Clone, Copy)] 6 | #[repr(transparent)] 7 | pub struct GameTime(red::GameTime); 8 | 9 | impl GameTime { 10 | pub fn new(days: u32, hours: u32, minutes: u32, seconds: u32) -> Self { 11 | let mut this = Self::default(); 12 | this.add_days(days); 13 | this.add_hours(hours); 14 | this.add_minutes(minutes); 15 | this.add_seconds(seconds); 16 | this 17 | } 18 | 19 | pub fn add_days(&mut self, days: u32) { 20 | self.0.seconds = self.0.seconds.saturating_add( 21 | days.saturating_mul(24) 22 | .saturating_mul(60) 23 | .saturating_mul(60), 24 | ); 25 | } 26 | 27 | pub fn add_hours(&mut self, hours: u32) { 28 | self.0.seconds = self 29 | .0 30 | .seconds 31 | .saturating_add(hours.saturating_mul(60).saturating_mul(60)); 32 | } 33 | 34 | pub fn add_minutes(&mut self, minutes: u32) { 35 | self.0.seconds = self.0.seconds.saturating_add(minutes.saturating_mul(60)); 36 | } 37 | 38 | pub fn add_seconds(&mut self, seconds: u32) { 39 | self.0.seconds = self.0.seconds.saturating_add(seconds); 40 | } 41 | 42 | pub fn sub_days(&mut self, days: u32) { 43 | self.0.seconds = self.0.seconds.saturating_sub( 44 | days.saturating_mul(24) 45 | .saturating_mul(60) 46 | .saturating_mul(60), 47 | ); 48 | } 49 | 50 | pub fn sub_hours(&mut self, hours: u32) { 51 | self.0.seconds = self 52 | .0 53 | .seconds 54 | .saturating_sub(hours.saturating_mul(60).saturating_mul(60)); 55 | } 56 | 57 | pub fn sub_minutes(&mut self, minutes: u32) { 58 | self.0.seconds = self.0.seconds.saturating_sub(minutes.saturating_mul(60)); 59 | } 60 | 61 | pub fn sub_seconds(&mut self, seconds: u32) { 62 | self.0.seconds = self.0.seconds.saturating_sub(seconds); 63 | } 64 | 65 | pub fn day(&self) -> u32 { 66 | unsafe { self.0.GetDay() } 67 | } 68 | 69 | pub fn hour(&self) -> u32 { 70 | unsafe { self.0.GetHour() } 71 | } 72 | 73 | pub fn minute(&self) -> u32 { 74 | unsafe { self.0.GetMinute() } 75 | } 76 | 77 | pub fn second(&self) -> u32 { 78 | unsafe { self.0.GetSecond() } 79 | } 80 | } 81 | 82 | impl std::fmt::Display for GameTime { 83 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 84 | let [day, hour, min, sec] = unsafe { self.0.ToString().0 }; 85 | write!(f, "{day}T{hour}:{min}:{sec}") 86 | } 87 | } 88 | 89 | impl PartialEq for GameTime { 90 | fn eq(&self, other: &Self) -> bool { 91 | self.0.seconds.eq(&other.0.seconds) 92 | } 93 | } 94 | 95 | impl Eq for GameTime {} 96 | 97 | impl PartialOrd for GameTime { 98 | fn partial_cmp(&self, other: &Self) -> Option { 99 | Some(self.cmp(other)) 100 | } 101 | } 102 | 103 | impl Ord for GameTime { 104 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 105 | self.0.seconds.cmp(&other.0.seconds) 106 | } 107 | } 108 | 109 | impl Hash for GameTime { 110 | fn hash(&self, state: &mut H) { 111 | self.0.seconds.hash(state); 112 | } 113 | } 114 | 115 | impl From for GameTime { 116 | fn from(seconds: u32) -> Self { 117 | Self(red::GameTime { seconds }) 118 | } 119 | } 120 | 121 | impl From for u32 { 122 | fn from(value: GameTime) -> Self { 123 | value.0.seconds 124 | } 125 | } 126 | 127 | #[cfg(feature = "time")] 128 | impl TryFrom for time::Time { 129 | type Error = time::error::ComponentRange; 130 | 131 | fn try_from(value: GameTime) -> Result { 132 | Self::from_hms( 133 | value.hour() as u8, 134 | value.minute() as u8, 135 | value.second() as u8, 136 | ) 137 | } 138 | } 139 | 140 | #[cfg(feature = "time")] 141 | impl From for GameTime { 142 | fn from(value: time::Time) -> Self { 143 | Self::new( 144 | 0, 145 | value.hour() as u32, 146 | value.minute() as u32, 147 | value.second() as u32, 148 | ) 149 | } 150 | } 151 | 152 | #[cfg(feature = "time")] 153 | impl std::ops::Add for GameTime { 154 | type Output = Self; 155 | 156 | fn add(self, rhs: time::Time) -> Self::Output { 157 | use std::ops::AddAssign; 158 | let mut copy = self; 159 | copy.add_assign(rhs); 160 | copy 161 | } 162 | } 163 | 164 | #[cfg(feature = "time")] 165 | impl std::ops::AddAssign for GameTime { 166 | fn add_assign(&mut self, rhs: time::Time) { 167 | self.add_hours(rhs.hour() as u32); 168 | self.add_minutes(rhs.minute() as u32); 169 | self.add_seconds(rhs.second() as u32); 170 | } 171 | } 172 | 173 | #[cfg(feature = "time")] 174 | impl std::ops::Sub for GameTime { 175 | type Output = Self; 176 | 177 | fn sub(self, rhs: time::Time) -> Self::Output { 178 | use std::ops::SubAssign; 179 | let mut copy = self; 180 | copy.sub_assign(rhs); 181 | copy 182 | } 183 | } 184 | 185 | #[cfg(feature = "time")] 186 | impl std::ops::SubAssign for GameTime { 187 | fn sub_assign(&mut self, rhs: time::Time) { 188 | self.sub_hours(rhs.hour() as u32); 189 | self.sub_minutes(rhs.minute() as u32); 190 | self.sub_seconds(rhs.second() as u32); 191 | } 192 | } 193 | 194 | #[cfg(feature = "chrono")] 195 | pub fn cyberpunk_epoch() -> chrono::DateTime { 196 | use chrono::TimeZone; 197 | chrono_tz::US::Pacific 198 | .with_ymd_and_hms(2077, 4, 16, 1, 24, 0) 199 | .unwrap() 200 | } 201 | 202 | #[cfg(feature = "chrono")] 203 | impl From for chrono::DateTime { 204 | fn from(value: GameTime) -> Self { 205 | // seconds being u32 it fits in i64, and nanos are zero 206 | Self::from_timestamp( 207 | cyberpunk_epoch().to_utc().timestamp() + value.0.seconds as i64, 208 | 0, 209 | ) 210 | .unwrap() 211 | } 212 | } 213 | 214 | #[cfg(feature = "chrono")] 215 | impl TryFrom> for GameTime { 216 | type Error = chrono::format::ParseErrorKind; 217 | 218 | fn try_from(value: chrono::DateTime) -> Result { 219 | if value < cyberpunk_epoch() { 220 | return Err(chrono::format::ParseErrorKind::OutOfRange); 221 | } 222 | Ok(Self::from( 223 | (value.timestamp() - cyberpunk_epoch().timestamp()) as u32, 224 | )) 225 | } 226 | } 227 | 228 | #[cfg(feature = "chrono")] 229 | impl chrono::Timelike for GameTime { 230 | fn hour(&self) -> u32 { 231 | Self::hour(self) 232 | } 233 | 234 | fn minute(&self) -> u32 { 235 | Self::minute(self) 236 | } 237 | 238 | fn second(&self) -> u32 { 239 | Self::second(self) 240 | } 241 | 242 | fn nanosecond(&self) -> u32 { 243 | 0 244 | } 245 | 246 | fn with_hour(&self, hour: u32) -> Option { 247 | if (0..=23).contains(&hour) { 248 | let mut copy = *self; 249 | unsafe { copy.0.SetHour(hour) }; 250 | return Some(copy); 251 | } 252 | None 253 | } 254 | 255 | fn with_minute(&self, min: u32) -> Option { 256 | if (0..=59).contains(&min) { 257 | let mut copy = *self; 258 | unsafe { copy.0.SetMinute(min) }; 259 | return Some(copy); 260 | } 261 | None 262 | } 263 | 264 | fn with_second(&self, sec: u32) -> Option { 265 | if (0..=59).contains(&sec) { 266 | let mut copy = *self; 267 | unsafe { copy.0.SetSecond(sec) }; 268 | return Some(copy); 269 | } 270 | None 271 | } 272 | 273 | /// GameTime does not support nanoseconds, so it will always return `None` 274 | fn with_nanosecond(&self, _: u32) -> Option { 275 | None 276 | } 277 | } 278 | 279 | #[cfg(test)] 280 | mod tests { 281 | use super::GameTime; 282 | 283 | #[test] 284 | fn instantiation() { 285 | let time = GameTime::new(2, 0, 7, 7); 286 | assert_eq!(time.day(), 2); 287 | assert_eq!(time.hour(), 0); 288 | assert_eq!(time.minute(), 7); 289 | assert_eq!(time.second(), 7); 290 | 291 | #[cfg(feature = "chrono")] 292 | { 293 | use chrono::Timelike; 294 | let time = time.with_minute(2).unwrap().with_second(2).unwrap(); 295 | assert_eq!(time.day(), 2); 296 | assert_eq!(time.hour(), 0); 297 | assert_eq!(time.minute(), 2); 298 | assert_eq!(time.second(), 2); 299 | } 300 | } 301 | 302 | #[test] 303 | #[cfg(feature = "chrono")] 304 | fn date() { 305 | use chrono::{DateTime, Datelike, Duration, Timelike, Utc}; 306 | 307 | use super::cyberpunk_epoch; 308 | let gt = GameTime::new(2, 0, 7, 7); 309 | let dt = DateTime::::from(gt); 310 | assert_eq!(dt.year(), 2077); 311 | assert_eq!(dt.month(), 4); 312 | assert_eq!(dt.day(), 18); 313 | assert_eq!(dt.hour(), 8); 314 | assert_eq!(dt.minute(), 31); 315 | assert_eq!(dt.second(), 7); 316 | 317 | let dt = cyberpunk_epoch().to_utc() 318 | + Duration::days(2) 319 | + Duration::minutes(7) 320 | + Duration::seconds(7); 321 | let gt = GameTime::try_from(dt).unwrap(); 322 | assert_eq!(gt.day(), 2); 323 | assert_eq!(gt.hour(), 0); 324 | assert_eq!(gt.minute(), 7); 325 | assert_eq!(gt.second(), 7); 326 | } 327 | 328 | #[test] 329 | #[cfg(feature = "time")] 330 | fn math() { 331 | let mut base = GameTime::new(2, 0, 7, 7); 332 | base += time::Time::from_hms(1, 2, 3).unwrap(); 333 | 334 | assert_eq!(base.day(), 2); 335 | assert_eq!(base.hour(), 1); 336 | assert_eq!(base.minute(), 9); 337 | assert_eq!(base.second(), 10); 338 | 339 | let mut base = GameTime::new(2, 0, 7, 7); 340 | base += time::Time::from_hms(23, 53, 59).unwrap(); 341 | 342 | assert_eq!(base.day(), 3); 343 | assert_eq!(base.hour(), 0); 344 | assert_eq!(base.minute(), 1); 345 | assert_eq!(base.second(), 6); 346 | } 347 | } 348 | -------------------------------------------------------------------------------- /src/types/hash.rs: -------------------------------------------------------------------------------- 1 | use std::iter::FusedIterator; 2 | use std::{mem, ptr, slice}; 3 | 4 | use super::{CName, IAllocator}; 5 | use crate::raw::root::RED4ext as red; 6 | 7 | const INVALID_INDEX: u32 = u32::MAX; 8 | 9 | /// A hash map. 10 | #[derive(Debug)] 11 | #[repr(transparent)] 12 | pub struct RedHashMap(red::HashMap); 13 | 14 | impl RedHashMap { 15 | #[inline] 16 | pub fn get(&self, key: &K) -> Option<&V> 17 | where 18 | K: Hash + PartialEq, 19 | { 20 | self.get_by_hash(key.hash()) 21 | } 22 | 23 | #[inline] 24 | pub fn get_mut(&mut self, key: &K) -> Option<&mut V> 25 | where 26 | K: Hash + PartialEq, 27 | { 28 | self.get_by_hash_mut(key.hash()) 29 | } 30 | 31 | pub fn insert(&mut self, key: K, value: V) -> Option 32 | where 33 | K: Hash + PartialEq, 34 | { 35 | let hash = key.hash(); 36 | 37 | if self.size() > 0 { 38 | if let Some(slot) = self.get_by_hash_mut(hash) { 39 | return Some(mem::replace(slot, value)); 40 | } 41 | } 42 | if self.size() + 1 > self.capacity() { 43 | self.realloc((self.capacity() + self.capacity() / 2).max(4)); 44 | } 45 | let (node_list, index_table) = self.split_mut(); 46 | Self::push_node(node_list, index_table, hash, key, value); 47 | self.0.size += 1; 48 | 49 | None 50 | } 51 | 52 | #[inline] 53 | pub fn iter(&self) -> Iter<'_, K, V> { 54 | self.into_iter() 55 | } 56 | 57 | #[inline] 58 | pub fn size(&self) -> u32 { 59 | self.0.size 60 | } 61 | 62 | #[inline] 63 | pub fn capacity(&self) -> u32 { 64 | self.0.capacity 65 | } 66 | 67 | fn get_by_hash(&self, hash: u32) -> Option<&V> { 68 | let mut cur = *self 69 | .indexes() 70 | .get((hash.checked_rem(self.capacity()))? as usize)?; 71 | while cur != INVALID_INDEX { 72 | let node = self.nodes().get(cur as usize)?; 73 | if node.hashedKey == hash { 74 | return Some(&node.value); 75 | } 76 | cur = node.next; 77 | } 78 | None 79 | } 80 | 81 | fn get_by_hash_mut(&mut self, hash: u32) -> Option<&mut V> { 82 | let mut cur = *self 83 | .indexes() 84 | .get((hash.checked_rem(self.capacity()))? as usize)?; 85 | while cur != INVALID_INDEX { 86 | let node = self.nodes_mut().get(cur as usize)?; 87 | if node.hashedKey == hash { 88 | return Some(&mut self.nodes_mut().get_mut(cur as usize)?.value); 89 | } 90 | cur = node.next; 91 | } 92 | None 93 | } 94 | 95 | fn realloc(&mut self, new_capacity: u32) { 96 | let new_cap_bytes = new_capacity as usize 97 | * (mem::size_of::>() + mem::size_of::()); 98 | let mem = unsafe { self.allocator().alloc_aligned(new_cap_bytes as _, 8) }; 99 | 100 | let mut node_list = red::HashMap_NodeList { 101 | nodes: mem, 102 | capacity: new_capacity, 103 | stride: mem::size_of::>() as _, 104 | ..Default::default() 105 | }; 106 | 107 | let index_table = unsafe { 108 | mem.byte_add(new_capacity as usize * mem::size_of::>()) 109 | } 110 | .cast::(); 111 | let index_table = unsafe { slice::from_raw_parts_mut(index_table, new_capacity as usize) }; 112 | index_table.iter_mut().for_each(|i| *i = INVALID_INDEX); 113 | 114 | if self.capacity() != 0 { 115 | if self.size() != 0 { 116 | let (self_nodes, self_indexes) = self.split_mut(); 117 | for idx in self_indexes { 118 | let mut cur = *idx; 119 | while cur != INVALID_INDEX { 120 | let old = unsafe { &*self_nodes.nodes.add(cur as usize) }; 121 | Self::push_node( 122 | &mut node_list, 123 | index_table, 124 | old.hashedKey, 125 | unsafe { ptr::read(&old.key) }, 126 | unsafe { ptr::read(&old.value) }, 127 | ); 128 | cur = old.next; 129 | } 130 | *idx = INVALID_INDEX; 131 | } 132 | } 133 | unsafe { self.allocator().free(self.0.nodeList.nodes) } 134 | } 135 | 136 | self.0.nodeList = node_list; 137 | self.0.indexTable = index_table.as_mut_ptr(); 138 | self.0.capacity = new_capacity; 139 | } 140 | 141 | fn push_node( 142 | node_list: &mut red::HashMap_NodeList, 143 | index_table: &mut [u32], 144 | hash: u32, 145 | key: K, 146 | value: V, 147 | ) { 148 | let node = Self::next_free_node(node_list).unwrap(); 149 | let next = &mut index_table[hash as usize % index_table.len()]; 150 | unsafe { 151 | (*node).hashedKey = hash; 152 | ptr::write(&mut (*node).key, key); 153 | ptr::write(&mut (*node).value, value); 154 | (*node).next = *next; 155 | *next = node.offset_from(node_list.nodes) as _; 156 | } 157 | } 158 | 159 | fn next_free_node( 160 | nl: &mut red::HashMap_NodeList, 161 | ) -> Option<*mut red::HashMap_Node> { 162 | if nl.nextIdx == INVALID_INDEX { 163 | return None; 164 | } 165 | if nl.nextIdx == nl.size { 166 | let node = unsafe { nl.nodes.add(nl.size as _) }; 167 | if nl.size + 1 < nl.capacity { 168 | nl.size += 1; 169 | nl.nextIdx += 1; 170 | } else { 171 | nl.nextIdx = INVALID_INDEX; 172 | } 173 | return Some(node); 174 | } 175 | let node = unsafe { nl.nodes.add(nl.nextIdx as _) }; 176 | nl.nextIdx = unsafe { (*node).next }; 177 | Some(node) 178 | } 179 | 180 | #[inline] 181 | fn split_mut(&mut self) -> (&mut red::HashMap_NodeList, &mut [u32]) { 182 | ( 183 | &mut self.0.nodeList, 184 | (self.0.capacity > 0) 185 | .then(|| unsafe { 186 | slice::from_raw_parts_mut(self.0.indexTable, self.0.capacity as _) 187 | }) 188 | .unwrap_or_default(), 189 | ) 190 | } 191 | 192 | #[inline] 193 | fn indexes(&self) -> &[u32] { 194 | (self.capacity() > 0) 195 | .then(|| unsafe { slice::from_raw_parts(self.0.indexTable, self.0.capacity as _) }) 196 | .unwrap_or_default() 197 | } 198 | 199 | #[inline] 200 | fn nodes(&self) -> &[red::HashMap_Node] { 201 | (self.capacity() > 0) 202 | .then(|| unsafe { 203 | slice::from_raw_parts(self.0.nodeList.nodes, self.0.nodeList.size as _) 204 | }) 205 | .unwrap_or_default() 206 | } 207 | 208 | #[inline] 209 | fn nodes_mut(&mut self) -> &mut [red::HashMap_Node] { 210 | (self.capacity() > 0) 211 | .then(|| unsafe { 212 | slice::from_raw_parts_mut(self.0.nodeList.nodes, self.0.nodeList.size as _) 213 | }) 214 | .unwrap_or_default() 215 | } 216 | 217 | #[inline] 218 | fn allocator(&self) -> &IAllocator { 219 | unsafe { &*(&self.0.allocator as *const _ as *const IAllocator) } 220 | } 221 | } 222 | 223 | impl<'a, K, V> IntoIterator for &'a RedHashMap { 224 | type IntoIter = Iter<'a, K, V>; 225 | type Item = (&'a K, &'a V); 226 | 227 | #[inline] 228 | fn into_iter(self) -> Self::IntoIter { 229 | Iter { 230 | current_index: INVALID_INDEX, 231 | indexes: self.indexes(), 232 | nodes: self.nodes(), 233 | } 234 | } 235 | } 236 | 237 | #[derive(Debug)] 238 | pub struct Iter<'a, K, V> { 239 | current_index: u32, 240 | indexes: &'a [u32], 241 | nodes: &'a [red::HashMap_Node], 242 | } 243 | 244 | impl<'a, K, V> Iterator for Iter<'a, K, V> { 245 | type Item = (&'a K, &'a V); 246 | 247 | fn next(&mut self) -> Option { 248 | if self.current_index != INVALID_INDEX { 249 | let node = &self.nodes[self.current_index as usize]; 250 | self.current_index = node.next; 251 | return Some((&node.key, &node.value)); 252 | } 253 | 254 | let (index, rem) = self.indexes.split_first()?; 255 | self.current_index = *index; 256 | self.indexes = rem; 257 | self.next() 258 | } 259 | } 260 | 261 | impl FusedIterator for Iter<'_, K, V> {} 262 | 263 | /// A trait for types that can be hashed. 264 | pub trait Hash { 265 | fn hash(&self) -> u32; 266 | } 267 | 268 | impl Hash for CName { 269 | #[inline] 270 | fn hash(&self) -> u32 { 271 | let hash = u64::from(*self); 272 | hash as u32 ^ (hash >> 32) as u32 273 | } 274 | } 275 | 276 | impl Hash for u32 { 277 | #[inline] 278 | fn hash(&self) -> u32 { 279 | *self 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /src/types/item_id.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use super::TweakDbId; 4 | use crate::raw::root::RED4ext as red; 5 | 6 | const DEFAULT_ITEM_ID_RNG_SEED: u32 = 2; 7 | 8 | #[derive(Default, Clone, Copy)] 9 | #[repr(transparent)] 10 | pub struct ItemId(red::ItemID); 11 | 12 | impl ItemId { 13 | #[inline] 14 | pub const fn new_from(id: TweakDbId) -> Self { 15 | Self(red::ItemID { 16 | tdbid: id.to_inner(), 17 | rngSeed: DEFAULT_ITEM_ID_RNG_SEED, 18 | uniqueCounter: 0, 19 | structure: GamedataItemStructure::BlueprintStackable as u8, 20 | flags: GameEItemIdFlag::None as u8, 21 | }) 22 | } 23 | 24 | pub fn structure(&self) -> GamedataItemStructure { 25 | self.0.structure.into() 26 | } 27 | 28 | pub fn flags(&self) -> GameEItemIdFlag { 29 | self.0.flags.into() 30 | } 31 | 32 | #[inline] 33 | pub fn tdbid(&self) -> TweakDbId { 34 | TweakDbId::from(unsafe { self.0.tdbid.__bindgen_anon_1.value }) 35 | } 36 | 37 | #[inline] 38 | pub const fn is_of_tdbid(&self, tdbid: TweakDbId) -> bool { 39 | unsafe { self.0.tdbid.__bindgen_anon_1.name }.hash == tdbid.hash() 40 | && unsafe { self.0.tdbid.__bindgen_anon_1.name }.length == tdbid.len() 41 | } 42 | 43 | pub fn is_valid(&self) -> bool { 44 | unsafe { self.0.IsValid() } 45 | } 46 | } 47 | 48 | impl fmt::Debug for ItemId { 49 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 50 | f.debug_struct("ItemId") 51 | .field("tdbid", &self.tdbid()) 52 | .field("structure", &self.structure()) 53 | .field("flags", &self.flags()) 54 | .finish() 55 | } 56 | } 57 | 58 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 59 | pub struct Seed(u32); 60 | 61 | impl Default for Seed { 62 | fn default() -> Self { 63 | Self(DEFAULT_ITEM_ID_RNG_SEED) 64 | } 65 | } 66 | 67 | #[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, Eq)] 68 | #[repr(u8)] 69 | pub enum GamedataItemStructure { 70 | #[default] 71 | BlueprintStackable = 0, 72 | Stackable = 1, 73 | Unique = 2, 74 | Count = 3, 75 | Invalid = 4, 76 | } 77 | 78 | impl From for GamedataItemStructure { 79 | fn from(value: u8) -> Self { 80 | match value { 81 | v if v == Self::BlueprintStackable as u8 => Self::BlueprintStackable, 82 | v if v == Self::Stackable as u8 => Self::Stackable, 83 | v if v == Self::Unique as u8 => Self::Unique, 84 | v if v == Self::Count as u8 => Self::Count, 85 | _ => Self::Invalid, 86 | } 87 | } 88 | } 89 | 90 | /// see [gameEItemIDFlag](https://nativedb.red4ext.com/gameEItemIDFlag) 91 | /// and [CET initialization](https://github.com/maximegmd/CyberEngineTweaks/blob/v1.27.1/src/scripting/Scripting.cpp#L311). 92 | #[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, Eq)] 93 | #[repr(u8)] 94 | pub enum GameEItemIdFlag { 95 | #[default] 96 | None = 0, 97 | Preview = 1, 98 | } 99 | 100 | impl From for GameEItemIdFlag { 101 | fn from(value: u8) -> Self { 102 | match value { 103 | v if v == Self::Preview as u8 => Self::Preview, 104 | _ => Self::None, 105 | } 106 | } 107 | } 108 | 109 | #[cfg(test)] 110 | mod tests { 111 | use std::ops::Not; 112 | 113 | use super::{ItemId, TweakDbId}; 114 | 115 | const V0: TweakDbId = TweakDbId::new("Items.FirstAidWhiffV0"); 116 | const V1: TweakDbId = TweakDbId::new("Items.FirstAidWhiffV1"); 117 | 118 | #[test] 119 | fn comparison() { 120 | assert_eq!(ItemId::new_from(V0).tdbid(), V0); 121 | assert!(ItemId::new_from(V0).is_of_tdbid(V0)); 122 | assert!(ItemId::new_from(V0).is_of_tdbid(V1).not()); 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/types/misc.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use const_combine::bounded::const_combine as combine; 4 | 5 | use crate::NativeRepr; 6 | use crate::raw::root::RED4ext as red; 7 | 8 | // temporary module, we should split it up into separate files 9 | 10 | #[repr(transparent)] 11 | pub struct LocalizationString(red::LocalizationString); 12 | 13 | #[derive(Debug)] 14 | #[repr(transparent)] 15 | pub struct NodeRef(red::NodeRef); 16 | 17 | #[derive(Debug)] 18 | #[repr(transparent)] 19 | pub struct DataBuffer(red::DataBuffer); 20 | 21 | #[derive(Debug)] 22 | #[repr(transparent)] 23 | pub struct DeferredDataBuffer(red::DeferredDataBuffer); 24 | 25 | #[derive(Debug)] 26 | #[repr(transparent)] 27 | pub struct SharedDataBuffer(red::SharedDataBuffer); 28 | 29 | #[derive(Debug, Default, Copy, Clone)] 30 | #[repr(transparent)] 31 | pub struct DateTime(red::CDateTime); 32 | 33 | #[derive(Debug, Default, Copy, Clone)] 34 | #[repr(transparent)] 35 | pub struct Guid(red::CGUID); 36 | 37 | #[derive(Debug)] 38 | #[repr(transparent)] 39 | pub struct EditorObjectId(red::EditorObjectID); 40 | 41 | #[derive(Debug, Default, Copy, Clone)] 42 | #[repr(transparent)] 43 | pub struct MessageResourcePath(red::MessageResourcePath); 44 | 45 | #[repr(transparent)] 46 | pub struct Variant(red::Variant); 47 | 48 | #[derive(Debug)] 49 | #[repr(transparent)] 50 | pub struct ResourceRef(red::ResourceReference); 51 | 52 | #[derive(Debug)] 53 | #[repr(transparent)] 54 | pub struct Curve(red::CurveData, PhantomData); 55 | 56 | #[derive(Debug)] 57 | #[repr(transparent)] 58 | pub struct MultiChannelCurve([u8; 56], PhantomData); 59 | 60 | #[derive(Debug)] 61 | #[repr(C)] 62 | pub struct StaticArray { 63 | entries: [T; N], 64 | size: u32, 65 | } 66 | 67 | const fn const_digit_str() -> &'static str { 68 | match N { 69 | 1 => "1", 70 | 2 => "2", 71 | 3 => "3", 72 | 4 => "4", 73 | 5 => "5", 74 | 6 => "6", 75 | 7 => "7", 76 | 8 => "8", 77 | _ => unimplemented!(), 78 | } 79 | } 80 | 81 | unsafe impl NativeRepr for StaticArray { 82 | const NAME: &'static str = combine!( 83 | combine!(combine!("[", const_digit_str::()), "]"), 84 | T::NAME 85 | ); 86 | } 87 | 88 | impl From<[T; N]> for StaticArray { 89 | fn from(entries: [T; N]) -> Self { 90 | Self { 91 | size: entries.len() as u32, 92 | entries, 93 | } 94 | } 95 | } 96 | 97 | impl StaticArray { 98 | #[inline] 99 | pub fn entries(&self) -> &[T] { 100 | &self.entries[..self.size as usize] 101 | } 102 | 103 | #[inline] 104 | pub fn size(&self) -> u32 { 105 | self.size 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/types/opt.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | /// A convenience type to explicitly mark 4 | /// a function argument as `opt T`. 5 | /// 6 | /// When left unspecified on Redscript side, 7 | /// it translates to its `Default` representation. 8 | #[derive(Default, Debug, Clone, Copy)] 9 | pub enum Opt { 10 | /// Value is specified and guaranteed to be non-`Default` value. 11 | NonDefault(T), 12 | /// `Default` value. 13 | #[default] 14 | Default, 15 | } 16 | 17 | impl From for Opt 18 | where 19 | T: Default + PartialEq, 20 | { 21 | fn from(value: T) -> Self { 22 | if value == T::default() { 23 | return Opt::Default; 24 | } 25 | Opt::NonDefault(value) 26 | } 27 | } 28 | 29 | impl Opt { 30 | pub fn into_option(self) -> Option { 31 | match self { 32 | Self::NonDefault(x) => Some(x), 33 | Self::Default => None, 34 | } 35 | } 36 | } 37 | 38 | impl Opt 39 | where 40 | T: Default, 41 | { 42 | pub fn unwrap_or_default(self) -> T { 43 | match self { 44 | Self::NonDefault(x) => x, 45 | Self::Default => T::default(), 46 | } 47 | } 48 | } 49 | 50 | impl fmt::Display for Opt 51 | where 52 | T: fmt::Display, 53 | { 54 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 55 | match self { 56 | Self::NonDefault(x) => write!(f, "{}", x), 57 | Self::Default => write!(f, "{}", ::default()), 58 | } 59 | } 60 | } 61 | 62 | impl PartialEq for Opt 63 | where 64 | T: Default + PartialEq, 65 | { 66 | fn eq(&self, other: &Opt) -> bool { 67 | match (self, other) { 68 | (Opt::NonDefault(lhs), Opt::NonDefault(rhs)) => lhs.eq(rhs), 69 | (Opt::NonDefault(lhs), Opt::Default) => lhs.eq(&T::default()), 70 | (Opt::Default, Opt::NonDefault(rhs)) => T::default().eq(rhs), 71 | (Opt::Default, Opt::Default) => true, 72 | } 73 | } 74 | } 75 | 76 | impl PartialEq for Opt 77 | where 78 | T: Default + PartialEq, 79 | { 80 | fn eq(&self, other: &T) -> bool { 81 | match self { 82 | Self::NonDefault(x) if x == other => true, 83 | Self::Default if other == &T::default() => true, 84 | _ => false, 85 | } 86 | } 87 | } 88 | 89 | impl Eq for Opt where T: Eq + Default {} 90 | 91 | impl PartialOrd for Opt 92 | where 93 | T: Default + PartialOrd + Ord, 94 | { 95 | fn partial_cmp(&self, other: &Self) -> Option { 96 | Some(self.cmp(other)) 97 | } 98 | } 99 | 100 | impl PartialOrd for Opt 101 | where 102 | T: Default + PartialOrd + Ord, 103 | { 104 | fn partial_cmp(&self, other: &T) -> Option { 105 | match (self, other) { 106 | (Self::NonDefault(lhs), rhs) => Some(lhs.cmp(rhs)), 107 | (Self::Default, rhs) => Some(T::default().cmp(rhs)), 108 | } 109 | } 110 | } 111 | 112 | impl Ord for Opt 113 | where 114 | T: Default + Ord, 115 | { 116 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 117 | match (self, other) { 118 | (Self::NonDefault(lhs), Self::NonDefault(rhs)) => lhs.cmp(rhs), 119 | (Self::NonDefault(lhs), Self::Default) => lhs.cmp(&T::default()), 120 | (Self::Default, Self::NonDefault(rhs)) => T::default().cmp(rhs), 121 | (Self::Default, Self::Default) => std::cmp::Ordering::Equal, 122 | } 123 | } 124 | } 125 | 126 | #[cfg(test)] 127 | mod tests { 128 | use super::Opt; 129 | 130 | #[test] 131 | fn transitivity() { 132 | assert!(Opt::NonDefault(0).eq(&Opt::Default)); 133 | assert!(Opt::::Default.eq(&Opt::NonDefault(0))); 134 | assert_eq!( 135 | Opt::NonDefault(0).cmp(&Opt::Default), 136 | std::cmp::Ordering::Equal 137 | ); 138 | assert_eq!( 139 | Opt::::Default.cmp(&Opt::NonDefault(0)), 140 | std::cmp::Ordering::Equal 141 | ); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/types/refs.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | use std::sync::atomic::{AtomicU32, Ordering}; 3 | use std::{mem, ptr}; 4 | 5 | use super::{CName, ISerializable, Type}; 6 | use crate::class::{NativeType, ScriptClass}; 7 | use crate::raw::root::RED4ext as red; 8 | use crate::repr::NativeRepr; 9 | use crate::systems::RttiSystem; 10 | use crate::{ClassKind, VoidPtr}; 11 | 12 | /// A reference counted shared pointer to a script class. 13 | #[repr(transparent)] 14 | pub struct Ref(BaseRef>); 15 | 16 | impl Ref { 17 | /// Creates a new reference to the class. 18 | #[inline] 19 | pub fn new() -> Option { 20 | Self::new_with(|_| {}) 21 | } 22 | 23 | /// Creates a new reference to the class and initializes it with the provided function. 24 | pub fn new_with(init: impl FnOnce(&mut T)) -> Option { 25 | let system = RttiSystem::get(); 26 | let class = system.get_class(CName::new(T::NAME))?; 27 | let mut this = Self::default(); 28 | Self::ctor(&mut this, class.instantiate().as_ptr().cast::()); 29 | 30 | init(T::Kind::fields_mut(this.0.instance_mut()?)); 31 | Some(this) 32 | } 33 | 34 | fn ctor(this: *mut Self, data: *mut T) { 35 | unsafe { 36 | let ctor = crate::fn_from_hash!(Handle_ctor, unsafe extern "C" fn(VoidPtr, VoidPtr)); 37 | ctor(this as *mut _ as VoidPtr, data as *mut _ as VoidPtr); 38 | } 39 | } 40 | 41 | /// Returns a reference to the fields of the class. 42 | /// 43 | /// # Safety 44 | /// The underlying value can be accessed mutably at any point through another copy of the 45 | /// [`Ref`]. Ideally, the caller should ensure that the returned reference is short-lived. 46 | #[inline] 47 | pub unsafe fn fields(&self) -> Option<&T> { 48 | Some(T::Kind::fields(self.0.instance()?)) 49 | } 50 | 51 | /// Returns a mutable reference to the fields of the class. 52 | /// 53 | /// # Safety 54 | /// The underlying value can be accessed mutably at any point through another copy of the 55 | /// [`Ref`]. Ideally, the caller should ensure that the returned reference is short-lived. 56 | #[inline] 57 | pub unsafe fn fields_mut(&mut self) -> Option<&mut T> { 58 | Some(T::Kind::fields_mut(self.0.instance_mut()?)) 59 | } 60 | 61 | /// Returns a reference to the instance of the class. 62 | /// 63 | /// # Safety 64 | /// The underlying value can be accessed mutably at any point through another copy of the 65 | /// [`Ref`]. Ideally, the caller should ensure that the returned reference is short-lived. 66 | #[inline] 67 | pub unsafe fn instance(&self) -> Option<&NativeType> { 68 | self.0.instance() 69 | } 70 | 71 | /// Converts the reference to a [`WeakRef`]. This will decrement the strong reference count 72 | /// and increment the weak reference count. 73 | #[inline] 74 | pub fn downgrade(self) -> WeakRef { 75 | self.0.inc_weak(); 76 | WeakRef(self.0.clone()) 77 | } 78 | 79 | /// Attempts to cast the reference to a reference of another class. 80 | /// Returns [`None`] if the target class is not compatible. 81 | pub fn cast(self) -> Option> 82 | where 83 | U: ScriptClass, 84 | { 85 | let inst = unsafe { (self.0.0.instance as *const ISerializable).as_ref() }?; 86 | inst.is_a::().then(|| unsafe { mem::transmute(self) }) 87 | } 88 | 89 | /// Returns whether the reference is null. 90 | #[inline] 91 | pub fn is_null(&self) -> bool { 92 | self.0.0.instance.is_null() 93 | } 94 | 95 | #[inline] 96 | pub fn is_exactly_a(&self) -> bool 97 | where 98 | U: ScriptClass, 99 | { 100 | unsafe { (self.0.0.instance as *const ISerializable).as_ref() } 101 | .is_some_and(ISerializable::is_exactly_a::) 102 | } 103 | 104 | #[inline] 105 | pub fn is_a(&self) -> bool 106 | where 107 | U: ScriptClass, 108 | { 109 | unsafe { (self.0.0.instance as *const ISerializable).as_ref() } 110 | .is_some_and(ISerializable::is_a::) 111 | } 112 | } 113 | 114 | impl Default for Ref { 115 | #[inline] 116 | fn default() -> Self { 117 | Self(BaseRef::default()) 118 | } 119 | } 120 | 121 | impl Clone for Ref { 122 | #[inline] 123 | fn clone(&self) -> Self { 124 | self.0.inc_strong(); 125 | Self(self.0.clone()) 126 | } 127 | } 128 | 129 | impl Drop for Ref { 130 | #[inline] 131 | fn drop(&mut self) { 132 | if self.0.dec_strong() && !self.0.0.instance.is_null() { 133 | let ptr = self.0.0.instance.cast::>(); 134 | unsafe { ptr::drop_in_place(ptr) } 135 | } 136 | } 137 | } 138 | 139 | unsafe impl Send for Ref {} 140 | unsafe impl Sync for Ref {} 141 | 142 | /// A weak reference to a script class. 143 | /// Before use, it must be upgraded to a strong reference using [`WeakRef::upgrade`]. 144 | #[repr(transparent)] 145 | pub struct WeakRef(BaseRef>); 146 | 147 | impl WeakRef { 148 | /// Attempts to upgrade the weak reference to a strong reference. 149 | /// Returns [`None`] if the strong reference count is zero. 150 | #[inline] 151 | pub fn upgrade(self) -> Option> { 152 | self.0.inc_strong_if_non_zero().then(|| Ref(self.0.clone())) 153 | } 154 | } 155 | 156 | impl Default for WeakRef { 157 | #[inline] 158 | fn default() -> Self { 159 | Self(BaseRef::default()) 160 | } 161 | } 162 | 163 | impl Clone for WeakRef { 164 | #[inline] 165 | fn clone(&self) -> Self { 166 | self.0.inc_weak(); 167 | Self(self.0.clone()) 168 | } 169 | } 170 | 171 | impl Drop for WeakRef { 172 | #[inline] 173 | fn drop(&mut self) { 174 | self.0.dec_weak(); 175 | } 176 | } 177 | 178 | unsafe impl Send for WeakRef {} 179 | unsafe impl Sync for WeakRef {} 180 | 181 | #[derive(Debug)] 182 | #[repr(transparent)] 183 | struct BaseRef(red::SharedPtrBase); 184 | 185 | impl BaseRef { 186 | #[inline] 187 | fn instance(&self) -> Option<&T> { 188 | unsafe { self.0.instance.as_ref() } 189 | } 190 | 191 | #[inline] 192 | fn instance_mut(&mut self) -> Option<&mut T> { 193 | unsafe { self.0.instance.as_mut() } 194 | } 195 | 196 | #[inline] 197 | fn inc_strong(&self) { 198 | if let Some(cnt) = self.ref_count() { 199 | cnt.strong().fetch_add(1, Ordering::Relaxed); 200 | } 201 | } 202 | 203 | fn inc_strong_if_non_zero(&self) -> bool { 204 | let Some(cnt) = self.ref_count() else { 205 | return false; 206 | }; 207 | 208 | cnt.strong() 209 | .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |x| { 210 | (x != 0).then(|| x + 1) 211 | }) 212 | .is_ok() 213 | } 214 | 215 | fn dec_strong(&mut self) -> bool { 216 | let Some(cnt) = self.ref_count() else { 217 | return false; 218 | }; 219 | 220 | if cnt.strong().fetch_sub(1, Ordering::Relaxed) == 1 { 221 | self.dec_weak(); 222 | true 223 | } else { 224 | false 225 | } 226 | } 227 | 228 | #[inline] 229 | fn inc_weak(&self) { 230 | if let Some(cnt) = self.ref_count() { 231 | cnt.weak_refs().fetch_add(1, Ordering::Relaxed); 232 | } 233 | } 234 | 235 | fn dec_weak(&mut self) { 236 | if self.0.refCount.is_null() { 237 | return; 238 | } 239 | unsafe { 240 | let dec_weak = crate::fn_from_hash!(Handle_DecWeakRef, unsafe extern "C" fn(VoidPtr)); 241 | dec_weak(self as *mut _ as VoidPtr); 242 | } 243 | } 244 | 245 | #[inline] 246 | fn ref_count(&self) -> Option<&RefCount> { 247 | unsafe { self.0.refCount.cast::().as_ref() } 248 | } 249 | } 250 | 251 | impl Default for BaseRef { 252 | #[inline] 253 | fn default() -> Self { 254 | Self(red::SharedPtrBase::default()) 255 | } 256 | } 257 | 258 | impl Clone for BaseRef { 259 | #[inline] 260 | fn clone(&self) -> Self { 261 | Self(red::SharedPtrBase { 262 | instance: self.0.instance, 263 | refCount: self.0.refCount, 264 | ..Default::default() 265 | }) 266 | } 267 | } 268 | 269 | #[derive(Debug, Clone, Copy)] 270 | #[repr(transparent)] 271 | struct RefCount(red::RefCnt); 272 | 273 | impl RefCount { 274 | #[inline] 275 | fn strong(&self) -> &AtomicU32 { 276 | unsafe { AtomicU32::from_ptr(&self.0.strongRefs as *const _ as _) } 277 | } 278 | 279 | #[inline] 280 | fn weak_refs(&self) -> &AtomicU32 { 281 | unsafe { AtomicU32::from_ptr(&self.0.weakRefs as *const _ as _) } 282 | } 283 | } 284 | 285 | /// A reference to local script data. 286 | #[derive(Debug)] 287 | #[repr(transparent)] 288 | pub struct ScriptRef<'a, T>(red::ScriptRef, PhantomData<&'a mut T>); 289 | 290 | impl<'a, T: NativeRepr> ScriptRef<'a, T> { 291 | /// Creates a new reference pointing to the provided value. 292 | pub fn new(val: &'a mut T) -> Option { 293 | let rtti = RttiSystem::get(); 294 | let inner = rtti.get_type(CName::new(T::NAME))?; 295 | let ref_ = red::ScriptRef { 296 | innerType: inner.as_raw() as *const _ as *mut red::CBaseRTTIType, 297 | ref_: val as *mut T, 298 | ..Default::default() 299 | }; 300 | Some(Self(ref_, PhantomData)) 301 | } 302 | 303 | /// Returns the value being referenced. 304 | #[inline] 305 | pub fn value(&self) -> Option<&T> { 306 | unsafe { self.0.ref_.as_ref() } 307 | } 308 | 309 | /// Returns the type of the value being referenced. 310 | #[inline] 311 | pub fn inner_type(&self) -> &Type { 312 | unsafe { &*(self.0.innerType.cast::()) } 313 | } 314 | 315 | /// Returns whether the reference is defined. 316 | #[inline] 317 | pub fn is_defined(&self) -> bool { 318 | !self.0.ref_.is_null() 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /src/types/res.rs: -------------------------------------------------------------------------------- 1 | use std::hash::Hash; 2 | use std::marker::PhantomData; 3 | use std::path::Path; 4 | 5 | use thiserror::Error; 6 | 7 | use crate::fnv1a64; 8 | use crate::raw::root::RED4ext as red; 9 | 10 | pub const MAX_LENGTH: usize = 216; 11 | 12 | /// An asynchronous resource reference. 13 | #[derive(Debug, Default, Clone, Copy)] 14 | #[repr(transparent)] 15 | pub struct RaRef(red::RaRef, PhantomData); 16 | 17 | impl RaRef { 18 | pub fn new(path: impl AsRef) -> Result { 19 | Ok(Self( 20 | red::RaRef { 21 | path: red::ResourcePath { 22 | hash: encode_path(path)?, 23 | }, 24 | }, 25 | PhantomData, 26 | )) 27 | } 28 | } 29 | 30 | impl PartialEq for RaRef { 31 | fn eq(&self, other: &Self) -> bool { 32 | self.0.path.hash.eq(&other.0.path.hash) 33 | } 34 | } 35 | 36 | impl Eq for RaRef {} 37 | 38 | impl PartialOrd for RaRef { 39 | fn partial_cmp(&self, other: &Self) -> Option { 40 | Some(self.cmp(other)) 41 | } 42 | } 43 | 44 | impl Ord for RaRef { 45 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 46 | self.0.path.hash.cmp(&other.0.path.hash) 47 | } 48 | } 49 | 50 | impl Hash for RaRef { 51 | fn hash(&self, state: &mut H) { 52 | self.0.path.hash.hash(state); 53 | } 54 | } 55 | 56 | #[derive(Debug, Default)] 57 | #[repr(transparent)] 58 | pub struct ResRef(red::ResRef); 59 | 60 | impl ResRef { 61 | pub fn new(path: impl AsRef) -> Result { 62 | Ok(Self(red::ResRef { 63 | resource: red::RaRef { 64 | path: red::ResourcePath { 65 | hash: encode_path(path)?, 66 | }, 67 | }, 68 | })) 69 | } 70 | } 71 | 72 | impl PartialEq for ResRef { 73 | fn eq(&self, other: &Self) -> bool { 74 | self.0.resource.path.hash.eq(&other.0.resource.path.hash) 75 | } 76 | } 77 | 78 | impl Eq for ResRef {} 79 | 80 | impl PartialOrd for ResRef { 81 | fn partial_cmp(&self, other: &Self) -> Option { 82 | Some(self.cmp(other)) 83 | } 84 | } 85 | 86 | impl Ord for ResRef { 87 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 88 | self.0.resource.path.hash.cmp(&other.0.resource.path.hash) 89 | } 90 | } 91 | 92 | impl Hash for ResRef { 93 | fn hash(&self, state: &mut H) { 94 | self.0.resource.path.hash.hash(state); 95 | } 96 | } 97 | 98 | impl Clone for ResRef { 99 | fn clone(&self) -> Self { 100 | Self(red::ResRef { 101 | resource: self.0.resource, 102 | }) 103 | } 104 | } 105 | 106 | fn encode_path(path: impl AsRef) -> Result { 107 | let sanitized = path 108 | .as_ref() 109 | .to_str() 110 | .ok_or(ResourcePathError::InvalidUnicode)?; 111 | let sanitized = sanitized 112 | .trim_start_matches(['\'', '\"']) 113 | .trim_end_matches(['\'', '\"']) 114 | .trim_start_matches(['/', '\\']) 115 | .trim_end_matches(['/', '\\']) 116 | .split(['/', '\\']) 117 | .filter(|comp| !comp.is_empty()) 118 | .map(str::to_ascii_lowercase) 119 | .reduce(|mut acc, e| { 120 | acc.push('\\'); 121 | acc.push_str(&e); 122 | acc 123 | }) 124 | .ok_or(ResourcePathError::Empty)?; 125 | if sanitized.len() > self::MAX_LENGTH { 126 | return Err(ResourcePathError::TooLong); 127 | } 128 | if Path::new(&sanitized) 129 | .components() 130 | .any(|x| !matches!(x, std::path::Component::Normal(_))) 131 | { 132 | return Err(ResourcePathError::NotCanonical); 133 | } 134 | Ok(fnv1a64(sanitized.as_bytes())) 135 | } 136 | 137 | #[derive(Debug, Error)] 138 | pub enum ResourcePathError { 139 | #[error("resource path should not be empty")] 140 | Empty, 141 | #[error("resource path should be less than {} characters", self::MAX_LENGTH)] 142 | TooLong, 143 | #[error( 144 | "resource path should be an absolute canonical path in an archive e.g. 'base\\mod\\character.ent'" 145 | )] 146 | NotCanonical, 147 | #[error("resource path should be valid UTF-8")] 148 | InvalidUnicode, 149 | } 150 | 151 | /// shortcut for ResRef creation. 152 | #[macro_export] 153 | macro_rules! res_ref { 154 | ($base:expr, /$lit:literal $($tt:tt)*) => { 155 | $crate::res_ref!($base.join($lit), $($tt)*) 156 | }; 157 | ($base:expr, ) => { 158 | $base 159 | }; 160 | ($lit:literal $($tt:tt)*) => { 161 | $crate::types::ResRef::new( 162 | $crate::res_ref!(::std::path::Path::new($lit), $($tt)*) 163 | ) 164 | }; 165 | } 166 | 167 | #[cfg(test)] 168 | mod tests { 169 | use super::{ResRef, encode_path}; 170 | use crate::fnv1a64; 171 | 172 | #[test] 173 | fn resource_path() { 174 | const TOO_LONG: &str = "base\\some\\archive\\path\\that\\is\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\very\\long\\and\\above\\216\\bytes"; 175 | assert!(TOO_LONG.as_bytes().len() > super::MAX_LENGTH); 176 | assert!(encode_path(TOO_LONG).is_err()); 177 | 178 | assert_eq!( 179 | encode_path("\'base/somewhere/in/archive/\'").unwrap(), 180 | fnv1a64(b"base\\somewhere\\in\\archive") 181 | ); 182 | assert_eq!( 183 | encode_path("\"MULTI\\\\SOMEWHERE\\\\IN\\\\ARCHIVE\"").unwrap(), 184 | fnv1a64(b"multi\\somewhere\\in\\archive") 185 | ); 186 | assert!(encode_path("..\\somewhere\\in\\archive\\custom.ent").is_err()); 187 | assert!(encode_path("base\\somewhere\\in\\archive\\custom.ent").is_ok()); 188 | assert!(encode_path("custom.ent").is_ok()); 189 | assert!(encode_path(".custom.ent").is_ok()); 190 | } 191 | 192 | #[test] 193 | fn res_path() { 194 | assert!(res_ref!("").is_err()); 195 | assert!(res_ref!(".." / "somewhere" / "in" / "archive" / "custom.ent").is_err()); 196 | assert!(res_ref!("base" / "somewhere" / "in" / "archive" / "custom.ent").is_ok()); 197 | assert!(res_ref!("custom.ent").is_ok()); 198 | assert!(res_ref!(".custom.ent").is_ok()); 199 | 200 | assert_eq!( 201 | res_ref!("base" / "somewhere" / "in" / "archive" / "custom.ent").unwrap(), 202 | ResRef::new(std::path::Path::new( 203 | "base\\somewhere\\in\\archive\\custom.ent" 204 | )) 205 | .unwrap() 206 | ); 207 | assert_eq!( 208 | res_ref!("custom.ent").unwrap(), 209 | ResRef::new(std::path::Path::new("custom.ent")).unwrap() 210 | ); 211 | assert_eq!( 212 | res_ref!(".custom.ent").unwrap(), 213 | ResRef::new(std::path::Path::new(".custom.ent")).unwrap() 214 | ); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /src/types/stack.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | use std::{iter, ptr}; 3 | 4 | use super::{CName, Function, IScriptable, Instr, OPCODE_SIZE, Type, ValueContainer}; 5 | use crate::raw::root::RED4ext as red; 6 | use crate::repr::NativeRepr; 7 | use crate::systems::RttiSystem; 8 | use crate::{FromRepr, VoidPtr}; 9 | 10 | /// A script stack frame. 11 | #[derive(Debug)] 12 | #[repr(transparent)] 13 | pub struct StackFrame(red::CStackFrame); 14 | 15 | impl StackFrame { 16 | /// Returns the current function of the stack frame. 17 | #[inline] 18 | pub fn func(&self) -> &Function { 19 | unsafe { &*(self.0.func as *const Function) } 20 | } 21 | 22 | /// Returns the parent stack frame. 23 | #[inline] 24 | pub fn parent(&self) -> Option<&StackFrame> { 25 | unsafe { (self.0.parent as *const StackFrame).as_ref() } 26 | } 27 | 28 | /// Returns an iterator over all parent stack frames. 29 | #[inline] 30 | pub fn parent_iter(&self) -> impl Iterator { 31 | iter::successors(self.parent(), |frame| frame.parent()) 32 | } 33 | 34 | /// Returns the context of the stack frame, the `this` pointer. 35 | #[inline] 36 | pub fn context(&self) -> Option<&IScriptable> { 37 | unsafe { (self.0.context as *const IScriptable).as_ref() } 38 | } 39 | 40 | /// Returns `true` if the stack frame has a code block. 41 | #[inline] 42 | pub fn has_code(&self) -> bool { 43 | !self.0.code.is_null() 44 | } 45 | 46 | /// Returns the memory address where local variables are stored. 47 | #[inline] 48 | pub fn locals(&self) -> ValueContainer { 49 | ValueContainer::new(self.0.localVars) 50 | } 51 | 52 | /// Returns the memory address where parameters are stored. 53 | #[inline] 54 | pub fn params(&self) -> ValueContainer { 55 | ValueContainer::new(self.0.params) 56 | } 57 | 58 | /// Interprets the code at specified offset as an instruction of type `I`. 59 | pub unsafe fn instr_at(&self, offset: isize) -> Option<&I> { 60 | if self.0.code.is_null() { 61 | return None; 62 | } 63 | unsafe { 64 | let ptr = self.0.code.offset(offset); 65 | (ptr.read() as u8 == I::OPCODE).then(|| &*(ptr.offset(OPCODE_SIZE) as *const I)) 66 | } 67 | } 68 | 69 | /// Steps over a single opcode (1 byte). 70 | #[inline] 71 | pub unsafe fn step(&mut self) { 72 | self.0.code = unsafe { self.0.code.offset(OPCODE_SIZE) }; 73 | } 74 | 75 | /// Retrieves the next argument from the stack frame. 76 | /// 77 | /// # Safety 78 | /// The type `T` must be the correct type of the next argument. 79 | #[inline] 80 | pub unsafe fn get_arg(&mut self) -> T 81 | where 82 | T: FromRepr, 83 | T::Repr: Default, 84 | { 85 | let mut repr = T::Repr::default(); 86 | unsafe { self.read_arg(&mut repr as *mut T::Repr as VoidPtr) }; 87 | T::from_repr(repr) 88 | } 89 | 90 | unsafe fn read_arg(&mut self, ptr: VoidPtr) { 91 | self.0.data = ptr::null_mut(); 92 | self.0.dataType = ptr::null_mut(); 93 | self.0.currentParam += 1; 94 | unsafe { 95 | let opcode = *self.0.code as u8; 96 | self.step(); 97 | red::OpcodeHandlers::Run(opcode, self.0.context, &mut self.0, ptr, ptr::null_mut()); 98 | } 99 | } 100 | 101 | /// Captures the state of stack arguments. 102 | /// 103 | /// Use its returned value 104 | /// with [restore_args](Self::restore_args) to restore the state of arguments. 105 | pub fn args_state(&self) -> StackArgsState { 106 | StackArgsState { 107 | code: self.0.code, 108 | data: self.0.data, 109 | data_type: self.0.dataType, 110 | } 111 | } 112 | 113 | /// Allows to reset the state of function arguments. 114 | /// 115 | /// # Safety 116 | /// The state must be saved **before** reading arguments. 117 | /// 118 | /// The state must be restored **before** passing it back to game code. 119 | /// 120 | /// Stack arguments should **neither** be _partially_ read, 121 | /// **nor** _partially_ restored. 122 | /// 123 | /// # Example 124 | /// ```rust 125 | /// # use red4ext_rs::{hooks, SdkEnv, types::{CName, EntityId, StackFrame, IScriptable}, VoidPtr}; 126 | /// # hooks! { 127 | /// # static ADD_HOOK: fn(i: *mut IScriptable, f: *mut StackFrame, a3: VoidPtr, a4: VoidPtr) -> (); 128 | /// # } 129 | /// # fn attach_my_hook(env: &SdkEnv, addr: unsafe extern "C" fn(i: *mut IScriptable, f: *mut StackFrame, a3: VoidPtr, a4: VoidPtr)) { 130 | /// # unsafe { env.attach_hook(ADD_HOOK, addr, detour) }; 131 | /// # } 132 | /// # fn should_detour(event_name: CName) -> bool { false } 133 | /// 134 | /// unsafe extern "C" fn detour( 135 | /// i: *mut IScriptable, 136 | /// f: *mut StackFrame, 137 | /// a3: VoidPtr, 138 | /// a4: VoidPtr, 139 | /// cb: unsafe extern "C" fn(i: *mut IScriptable, f: *mut StackFrame, a3: VoidPtr, a4: VoidPtr), 140 | /// ) { 141 | /// let frame = &mut *f; 142 | /// 143 | /// // stack must be saved before reading stack function parameters 144 | /// let state = frame.args_state(); 145 | /// 146 | /// // assuming our function accepts these 3 parameters 147 | /// let event_name: CName = StackFrame::get_arg(frame); 148 | /// let entity_id: EntityId = StackFrame::get_arg(frame); 149 | /// let emitter_name: CName = StackFrame::get_arg(frame); 150 | /// 151 | /// if should_detour(event_name) { 152 | /// // do something else... 153 | /// } else { 154 | /// // since we've read stack function arguments, 155 | /// // stack arguments must be restored before callback. 156 | /// frame.restore_args(state); 157 | /// cb(i, f, a3, a4); 158 | /// } 159 | /// } 160 | /// ``` 161 | pub unsafe fn restore_args(&mut self, state: StackArgsState) { 162 | self.0.code = state.code; 163 | self.0.data = state.data; 164 | self.0.dataType = state.data_type; 165 | self.0.currentParam = 0; 166 | } 167 | } 168 | 169 | /// A stack argument to be passed to a function. 170 | #[derive(Debug)] 171 | #[repr(transparent)] 172 | pub struct StackArg<'a>(red::CStackType, PhantomData<&'a mut ()>); 173 | 174 | impl<'a> StackArg<'a> { 175 | /// Creates a new stack argument from a reference to a value. 176 | pub fn new(val: &'a mut A) -> Option { 177 | let type_ = if A::NAME == "Void" { 178 | ptr::null_mut() 179 | } else { 180 | let rtti = RttiSystem::get(); 181 | rtti.get_type(CName::new(A::NAME))?.as_raw() as *const _ as *mut red::CBaseRTTIType 182 | }; 183 | let inner = red::CStackType { 184 | type_, 185 | value: val as *const A as VoidPtr, 186 | }; 187 | Some(Self(inner, PhantomData)) 188 | } 189 | 190 | /// Returns the type of the stack argument. 191 | #[inline] 192 | pub fn type_(&self) -> Option<&Type> { 193 | unsafe { self.0.type_.cast::().as_ref() } 194 | } 195 | 196 | #[inline] 197 | pub(super) fn as_raw_mut(&mut self) -> &mut red::CStackType { 198 | &mut self.0 199 | } 200 | } 201 | 202 | /// Snapshot of the state of stack arguments. 203 | pub struct StackArgsState { 204 | code: *mut i8, 205 | data: VoidPtr, 206 | data_type: *mut red::CBaseRTTIType, 207 | } 208 | -------------------------------------------------------------------------------- /src/types/string.rs: -------------------------------------------------------------------------------- 1 | use std::ffi::{CStr, CString}; 2 | use std::{fmt, ops, ptr}; 3 | 4 | use crate::raw::root::RED4ext as red; 5 | 6 | /// A dynamically allocated string. 7 | #[repr(transparent)] 8 | pub struct RedString(red::CString); 9 | 10 | impl RedString { 11 | /// Creates a new empty string. 12 | #[inline] 13 | pub fn new() -> Self { 14 | Self(unsafe { red::CString::new(ptr::null_mut()) }) 15 | } 16 | } 17 | 18 | impl Default for RedString { 19 | #[inline] 20 | fn default() -> Self { 21 | Self::new() 22 | } 23 | } 24 | 25 | impl Clone for RedString { 26 | #[inline] 27 | fn clone(&self) -> Self { 28 | Self::from(self.as_ref()) 29 | } 30 | } 31 | 32 | impl ops::Deref for RedString { 33 | type Target = CStr; 34 | 35 | #[inline] 36 | fn deref(&self) -> &Self::Target { 37 | unsafe { CStr::from_ptr(self.0.c_str()) } 38 | } 39 | } 40 | 41 | impl From<&CStr> for RedString { 42 | #[inline] 43 | fn from(value: &CStr) -> Self { 44 | Self(unsafe { red::CString::new1(value.as_ptr(), ptr::null_mut()) }) 45 | } 46 | } 47 | 48 | impl From<&str> for RedString { 49 | #[inline] 50 | fn from(value: &str) -> Self { 51 | Self(unsafe { 52 | red::CString::new2( 53 | value.as_ptr() as *const i8, 54 | value.len() as u32, 55 | ptr::null_mut(), 56 | ) 57 | }) 58 | } 59 | } 60 | 61 | impl From for RedString { 62 | #[inline] 63 | fn from(value: CString) -> Self { 64 | value.as_c_str().into() 65 | } 66 | } 67 | 68 | impl From for RedString { 69 | #[inline] 70 | fn from(value: String) -> Self { 71 | RedString::from(crate::truncated_cstring(value)) 72 | } 73 | } 74 | 75 | impl From for String { 76 | #[inline] 77 | fn from(value: RedString) -> Self { 78 | value.to_string_lossy().into_owned() 79 | } 80 | } 81 | 82 | impl AsRef for RedString { 83 | #[inline] 84 | fn as_ref(&self) -> &CStr { 85 | self 86 | } 87 | } 88 | 89 | impl fmt::Debug for RedString { 90 | #[inline] 91 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 92 | write!(f, "{:?}", self.as_ref()) 93 | } 94 | } 95 | 96 | impl fmt::Display for RedString { 97 | #[inline] 98 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 99 | write!(f, "{}", self.to_string_lossy()) 100 | } 101 | } 102 | 103 | impl Drop for RedString { 104 | #[inline] 105 | fn drop(&mut self) { 106 | unsafe { self.0.destruct() } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/types/sync.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | use std::ops::{Deref, DerefMut}; 3 | use std::ptr::NonNull; 4 | 5 | use crate::raw::root::RED4ext as red; 6 | 7 | /// A read-write spin lock read guard. Permits any number of readers to access the locked data. 8 | pub struct RwSpinLockReadGuard<'a, T> { 9 | lock: &'a red::SharedSpinLock, 10 | value: NonNull, 11 | phantom: PhantomData<&'a T>, 12 | } 13 | 14 | impl<'a, T> RwSpinLockReadGuard<'a, T> { 15 | #[inline] 16 | pub(crate) unsafe fn new(lock: &'a red::SharedSpinLock, value: NonNull) -> Self { 17 | unsafe { red::SharedSpinLock_LockShared(lock as *const _ as *mut red::SharedSpinLock) }; 18 | Self { 19 | value, 20 | lock, 21 | phantom: PhantomData, 22 | } 23 | } 24 | } 25 | 26 | impl Deref for RwSpinLockReadGuard<'_, T> { 27 | type Target = T; 28 | 29 | #[inline] 30 | fn deref(&self) -> &Self::Target { 31 | unsafe { self.value.as_ref() } 32 | } 33 | } 34 | 35 | impl Drop for RwSpinLockReadGuard<'_, T> { 36 | #[inline] 37 | fn drop(&mut self) { 38 | unsafe { 39 | red::SharedSpinLock_UnlockShared(self.lock as *const _ as *mut red::SharedSpinLock) 40 | }; 41 | } 42 | } 43 | 44 | /// A read-write spin lock write guard. Permits only one thread at a time to access the locked data. 45 | pub struct RwSpinLockWriteGuard<'a, T> { 46 | lock: &'a red::SharedSpinLock, 47 | value: NonNull, 48 | phantom: PhantomData<&'a mut T>, 49 | } 50 | 51 | impl<'a, T> RwSpinLockWriteGuard<'a, T> { 52 | #[inline] 53 | pub(crate) unsafe fn new(lock: &'a red::SharedSpinLock, value: NonNull) -> Self { 54 | unsafe { red::SharedSpinLock_Lock(lock as *const _ as *mut red::SharedSpinLock) }; 55 | Self { 56 | value, 57 | lock, 58 | phantom: PhantomData, 59 | } 60 | } 61 | } 62 | 63 | impl Deref for RwSpinLockWriteGuard<'_, T> { 64 | type Target = T; 65 | 66 | #[inline] 67 | fn deref(&self) -> &Self::Target { 68 | unsafe { self.value.as_ref() } 69 | } 70 | } 71 | 72 | impl DerefMut for RwSpinLockWriteGuard<'_, T> { 73 | #[inline] 74 | fn deref_mut(&mut self) -> &mut Self::Target { 75 | unsafe { &mut *self.value.as_ptr() } 76 | } 77 | } 78 | 79 | impl Drop for RwSpinLockWriteGuard<'_, T> { 80 | #[inline] 81 | fn drop(&mut self) { 82 | unsafe { red::SharedSpinLock_Unlock(self.lock as *const _ as *mut red::SharedSpinLock) }; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/types/tweak_db_id.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | use std::hash::Hash; 3 | 4 | use const_crc32::{crc32, crc32_seed}; 5 | 6 | use crate::raw::root::RED4ext as red; 7 | 8 | #[derive(Default, Clone, Copy)] 9 | #[repr(C, align(4))] 10 | pub struct TweakDbId(red::TweakDBID); 11 | 12 | impl TweakDbId { 13 | #[inline] 14 | const fn new_with(hash: u32, length: u8, offset: [u8; 3]) -> Self { 15 | Self(red::TweakDBID { 16 | __bindgen_anon_1: red::TweakDBID__bindgen_ty_1 { 17 | name: red::TweakDBID__bindgen_ty_1__bindgen_ty_1 { 18 | hash, 19 | length, 20 | tdbOffsetBE: offset, 21 | }, 22 | }, 23 | }) 24 | } 25 | 26 | #[inline] 27 | pub const fn new(str: &str) -> Self { 28 | assert!(str.len() <= u8::MAX as usize); 29 | Self::new_with(crc32(str.as_bytes()), str.len() as u8, [0, 0, 0]) 30 | } 31 | 32 | #[inline] 33 | pub const fn new_from_base(base: TweakDbId, str: &str) -> Self { 34 | let base_hash = unsafe { base.0.__bindgen_anon_1.name.hash }; 35 | let base_length = unsafe { base.0.__bindgen_anon_1.name.length }; 36 | assert!((base_length as usize + str.len()) <= u8::MAX as usize); 37 | Self::new_with( 38 | crc32_seed(str.as_bytes(), base_hash), 39 | str.len() as u8 + base_length, 40 | [0, 0, 0], 41 | ) 42 | } 43 | 44 | pub fn is_valid(self) -> bool { 45 | unsafe { self.0.IsValid() } 46 | } 47 | 48 | pub fn has_tdb_offset(self) -> bool { 49 | self.tdb_offset() != 0 50 | } 51 | 52 | pub fn tdb_offset(self) -> i32 { 53 | let [b1, b2, b3] = unsafe { self.0.__bindgen_anon_1.name }.tdbOffsetBE; 54 | i32::from_be_bytes([0, b1, b2, b3]) 55 | } 56 | 57 | pub fn with_tdb_offset(self, offset: i32) -> Self { 58 | assert!(offset <= (i8::MAX as i32 * i8::MAX as i32 * i8::MAX as i32)); 59 | assert!(offset >= (i8::MIN as i32 * i8::MIN as i32 * i8::MIN as i32)); 60 | let [_, b1, b2, b3] = offset.to_be_bytes(); 61 | Self::new_with( 62 | unsafe { self.0.__bindgen_anon_1.name }.hash, 63 | unsafe { self.0.__bindgen_anon_1.name }.length, 64 | [b1, b2, b3], 65 | ) 66 | } 67 | 68 | pub(super) const fn hash(&self) -> u32 { 69 | unsafe { self.0.__bindgen_anon_1.name }.hash 70 | } 71 | 72 | pub(super) const fn len(&self) -> u8 { 73 | unsafe { self.0.__bindgen_anon_1.name }.length 74 | } 75 | 76 | pub(super) const fn to_inner(self) -> red::TweakDBID { 77 | self.0 78 | } 79 | } 80 | 81 | impl Debug for TweakDbId { 82 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 83 | f.debug_tuple("TweakDbId") 84 | .field(&unsafe { self.0.__bindgen_anon_1.value }) 85 | .finish() 86 | } 87 | } 88 | 89 | impl PartialEq for TweakDbId { 90 | fn eq(&self, other: &Self) -> bool { 91 | u64::from(*self).eq(&u64::from(*other)) 92 | } 93 | } 94 | 95 | impl Eq for TweakDbId {} 96 | 97 | impl PartialOrd for TweakDbId { 98 | fn partial_cmp(&self, other: &Self) -> Option { 99 | Some(self.cmp(other)) 100 | } 101 | } 102 | 103 | impl Ord for TweakDbId { 104 | fn cmp(&self, other: &Self) -> std::cmp::Ordering { 105 | u64::from(*self).cmp(&u64::from(*other)) 106 | } 107 | } 108 | 109 | impl From for TweakDbId { 110 | fn from(value: u64) -> Self { 111 | Self(red::TweakDBID { 112 | __bindgen_anon_1: red::TweakDBID__bindgen_ty_1 { value }, 113 | }) 114 | } 115 | } 116 | 117 | impl From for u64 { 118 | fn from(value: TweakDbId) -> Self { 119 | unsafe { value.0.__bindgen_anon_1.value } 120 | } 121 | } 122 | 123 | impl Hash for TweakDbId { 124 | fn hash(&self, state: &mut H) { 125 | u64::from(*self).hash(state); 126 | } 127 | } 128 | 129 | #[cfg(test)] 130 | mod tests { 131 | use super::TweakDbId; 132 | 133 | #[test] 134 | fn conversion() { 135 | assert_eq!( 136 | TweakDbId::new("Items.FirstAidWhiffV0"), 137 | TweakDbId::from(90_628_141_458) 138 | ); 139 | assert_eq!( 140 | u64::from(TweakDbId::new("Items.FirstAidWhiffV0")), 141 | 90_628_141_458 142 | ); 143 | } 144 | 145 | #[test] 146 | fn mutation() { 147 | let original = TweakDbId::from(90_628_141_458); 148 | let modified = original.with_tdb_offset(128); 149 | assert_eq!(original.tdb_offset(), 0); 150 | assert_eq!(modified.tdb_offset(), 128); 151 | } 152 | } 153 | --------------------------------------------------------------------------------