diff --git a/Cargo.lock b/Cargo.lock
index 296e4c5..fc7c309 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3981,10 +3981,11 @@ dependencies = [
[[package]]
name = "openrage-app"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"anyhow",
"dirs",
+ "flate2",
"memchr",
"openrage-plugins",
"png",
@@ -4003,7 +4004,7 @@ dependencies = [
[[package]]
name = "openrage-cli"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"anyhow",
"clap",
@@ -4022,7 +4023,7 @@ dependencies = [
[[package]]
name = "openrage-gui"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"anyhow",
"arboard",
@@ -4049,7 +4050,7 @@ dependencies = [
[[package]]
name = "openrage-plugins"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"anyhow",
"dirs",
@@ -4068,6 +4069,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "opus-rs"
+version = "0.1.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bafbcaf2ed381cdf68ced4ed8d16517de90ffd7424e36f0b9e45d67fbe30b1f9"
+
[[package]]
name = "orbclient"
version = "0.3.55"
@@ -4528,11 +4535,11 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rage-core"
-version = "0.5.0"
+version = "0.6.0"
[[package]]
name = "rage-crypto"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"aes",
"flate2",
@@ -4543,13 +4550,15 @@ dependencies = [
[[package]]
name = "rage-formats"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"flate2",
"lewton",
+ "opus-rs",
"png",
"rage-core",
"rage-resource",
+ "roxmltree",
"symphonia",
"texpresso",
"texture2ddecoder",
@@ -4558,11 +4567,13 @@ dependencies = [
[[package]]
name = "rage-index"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"flate2",
"rage-core",
"rage-crypto",
+ "rage-formats",
+ "rage-resource",
"rage-rpf",
"rayon",
"rusqlite",
@@ -4571,7 +4582,7 @@ dependencies = [
[[package]]
name = "rage-mods"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"rage-crypto",
"rage-rpf",
@@ -4579,7 +4590,7 @@ dependencies = [
[[package]]
name = "rage-resource"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"flate2",
"thiserror 2.0.21",
@@ -4587,7 +4598,7 @@ dependencies = [
[[package]]
name = "rage-rpf"
-version = "0.5.0"
+version = "0.6.0"
dependencies = [
"flate2",
"memchr",
@@ -4603,7 +4614,7 @@ dependencies = [
[[package]]
name = "rage-tfit2"
-version = "0.5.0"
+version = "0.6.0"
[[package]]
name = "rand"
diff --git a/Cargo.toml b/Cargo.toml
index 9bc00e7..de977b8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
-version = "0.5.0"
+version = "0.6.0"
edition = "2024"
license = "GPL-3.0-only"
repository = "https://github.com/Two-Play/openrage"
@@ -13,14 +13,14 @@ authors = ["OpenRAGE contributors"]
rust-version = "1.99"
[workspace.dependencies]
-rage-core = { path = "crates/rage-core", version = "0.5.0" }
-rage-crypto = { path = "crates/rage-crypto", version = "0.5.0" }
-rage-tfit2 = { path = "crates/rage-tfit2", version = "0.5.0" }
-rage-rpf = { path = "crates/rage-rpf", version = "0.5.0", features = ["rdr2"] }
-rage-index = { path = "crates/rage-index", version = "0.5.0" }
-rage-mods = { path = "crates/rage-mods", version = "0.5.0" }
-rage-resource = { path = "crates/rage-resource", version = "0.5.0" }
-rage-formats = { path = "crates/rage-formats", version = "0.5.0" }
+rage-core = { path = "crates/rage-core", version = "0.6.0" }
+rage-crypto = { path = "crates/rage-crypto", version = "0.6.0" }
+rage-tfit2 = { path = "crates/rage-tfit2", version = "0.6.0" }
+rage-rpf = { path = "crates/rage-rpf", version = "0.6.0", features = ["rdr2"] }
+rage-index = { path = "crates/rage-index", version = "0.6.0" }
+rage-mods = { path = "crates/rage-mods", version = "0.6.0" }
+rage-resource = { path = "crates/rage-resource", version = "0.6.0" }
+rage-formats = { path = "crates/rage-formats", version = "0.6.0" }
aes = "0.8"
anyhow = "1"
diff --git a/NOTICE.md b/NOTICE.md
index 5a60ca7..ed9b825 100644
--- a/NOTICE.md
+++ b/NOTICE.md
@@ -51,6 +51,58 @@ Vorbis audio (Red Dead Redemption 2) is decoded with lewton
(https://github.com/RustAudio/lewton), licensed under the MIT or Apache-2.0
license.
+## opus-rs
+
+Opus audio (GTA VI) is decoded with opus-rs
+(https://github.com/restsend/opus-rs), a port of libopus, licensed under the
+BSD 3-Clause licence.
+
+## Librempeg
+
+The Bink 2 video and audio decoder in `crates/rage-formats/src/bink` is a port
+to Rust of the one in Librempeg (https://github.com/librempeg/librempeg;
+`libavcodec/bink2.c`, `bink2.h`, `bink2g.h`, `libavcodec/binkaudio.c` and
+`libavformat/bink.c`), which is licensed under the GNU General Public License
+version 3 or later and used here under version 3:
+
+```
+Copyright (c) 2014 Konstantin Shishkov
+Copyright (c) 2019 Paul B Mahol
+Copyright (c) 2007-2011 Peter Ross
+Copyright (c) 2009 Daniel Verkamp
+```
+
+## FFmpeg
+
+The Bink 1 video decoder in `crates/rage-formats/src/bink` (`video1.rs`,
+`tables1.rs`) is a port to Rust of the one in FFmpeg (https://ffmpeg.org;
+`libavcodec/bink.c`, `binkdata.h` and `binkdsp.c`), which is licensed under the
+GNU Lesser General Public License version 2.1 or later and used here under the
+GNU General Public License version 3, as section 3 of the former allows:
+
+```
+Copyright (c) 2009 Konstantin Shishkov
+Copyright (c) 2011 Peter Ross
+```
+
+Bink is a trademark of Epic Games Tools LLC (RAD Game Tools). OpenRAGE is not
+affiliated with them and contains none of their code.
+
+## Leonida
+
+What is known about GTA VI's formats (RPF9 archives, audio containers, PSIN
+and RBF0 metadata, texture pools) comes from the documentation of Leonida
+(https://github.com/ItsNotRexed/Leonida, GPL-3.0). The PSIN reader in
+`crates/rage-formats/src/psin.rs` follows its `tools/psin_data.py`, the
+texture pool reader in `crates/rage-formats/src/ttpf.rs` its
+`tools/ttpf_mips.py` and `tools/tex_headers.py`.
+
+## rpf9-explorer
+
+The layout of GTA VI's models (`crates/rage-formats/src/drawable6.rs`) is the
+one found by rpf9-explorer (https://github.com/breadbbbb/rpf9-explorer). Its
+decoder was read to learn the layout; no code was taken from it.
+
## RDR2-RPF-Tool
The TFIT2-CBC cipher and the strided file encryption of Red Dead Redemption 2
diff --git a/README.md b/README.md
index ca1f5ea..4db5214 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,12 @@
# OpenRAGE
-**The open-source successor to OpenIV — mod GTA V and explore Red Dead Redemption 2 on Linux and Windows.**
+**The open-source successor to OpenIV — mod GTA V and Red Dead Redemption 2, and explore GTA VI, on Linux and Windows.**
+
+### 🌴 New: GTA VI works!
+
+**Browse and search its RPF9 archives, view the whole map in 3D, models, textures and animations, play sounds and videos.**
+[What works in GTA VI](https://two-play.github.io/openrage/gta-vi/) (read-only preview, with your own copy of the game)
Browse and search every archive, preview textures, models, sounds and animations, read metadata as XML,
edit game text and install `.oiv` packages — compatible with OpenIV's `mods` folder, with undo.
@@ -34,13 +39,13 @@ edit game text and install `.oiv` packages — compatible with OpenIV's `mods` f
OpenIV's last release was in January 2022. OpenRAGE picks up where it left off and stays compatible with it.
+- **GTA VI explorer (preview):** browse and extract RPF9 archives, with folders, names and nested archives; see the whole map in 3D; preview models with their materials, collisions, navigation meshes, textures, metadata and text tables, play sounds and videos, search names and text, list clip dictionaries and play them on vehicles, weapons, props and parts of people.
- **Explorer and search:** archives, even nested ones, open like folders, as a list or as icons; names, hashes and full text of the whole game in milliseconds.
-- **Every major format:** textures, models, audio, animations, metadata as XML, collisions, paths, nav meshes, cutscenes, scripts, game text.
+- **Every major format:** textures, models, audio, videos (Bink 1 and 2, with a player), animations, metadata as XML, collisions, paths, nav meshes, cutscenes, scripts, game text.
- **Coming from OpenIV?** Your `mods` folder and `.oiv` packages work as they are ([how to switch](https://two-play.github.io/openrage/getting-started/#coming-from-openiv)).
- **Mods, safely:** changes go to OpenIV's `mods` folder, never into your game files; every change and every `.oiv` package can be undone.
- **Models in:** replace props and vehicle bodies of GTA V Enhanced with your own OBJ models; doors and bonnets keep moving (preview).
- **ASI mods:** see and switch GTA V's ASI mods, and on Linux let Proton load the ASI loader with one click.
-- **Ready for GTA VI:** support follows as fast as possible once GTA VI comes to PC.
- **Tested on the whole game:** every format is checked against every file of GTA V ([details](https://two-play.github.io/openrage/#status)).
@@ -61,16 +66,20 @@ More screenshots and all features: **[two-play.github.io/openrage](https://two-p
| Game | Archives | Formats |
|---|---|---|
| **GTA V** (Legacy & Enhanced) | ✅ read and edit (mods folder, with undo) | ✅ textures (also inside models) · models · audio · animations · metadata · text · collisions · paths · cutscenes · scripts · ASI mods (manager, Proton fix on Linux) · ◐ model import from OBJ with compressed textures and detail levels (Enhanced `.ydr` and vehicle bodies `.yft`, preview; explorer via the OBJ tools plugin) |
-| **Red Dead Redemption 2** | ✅ read, with keys from your own game | ◐ textures · models · texts · metadata · audio · animations · ped outfits (read-only) |
-| **GTA VI** | 🔜 next: as fast as possible once it comes to PC | – |
+| **GTA VI** (Scarlett build, preview) | ◐ read-only RPF9: the table of contents is read with the game's own executable (one build); without it, a recovery view. Names of models and clips are known, of some other types not | ◐ models with skeletons · clip dictionaries (`.#cd`) · texture pools (`.ttpf`) and dictionaries (`.#td`; no volumes) · collisions (`.#bn`) · navigation meshes (`.#nv`) · maps in 3D · metadata, maps and text tables as XML (`.#mt`, `.#map`, `.#typ`, `.#ldbmt` and others) · audio · videos |
+| **Red Dead Redemption 2** | ✅ read, with keys from your own game · ◐ edit (Lenny's Mod Loader `lml/replace` folder, with undo; nested archives rewritten; not yet tried in the game) | ◐ textures (replace same-shape) · models with moving parts and cloth · texts · metadata · audio · animations on fitting models · ped outfits (read-only) |
| **GTA IV** (Complete Edition) | ✅ read (IMG3, RPF2, RPF3), key from your own `GTAIV.exe` | ◐ textures · models · collisions · animations · text · scripts · maps in 3D · cutscenes (played with their cast, camera, subtitles and particle effects) · particle effect lists (`.wpfl`) · editing `.img`, `.rpf`, placement files, loose files and textures (`.wtd`, inside `.wdr`) (update folder, or the game files with originals kept) |
-**Plugins** (API 0.3, preview): sandboxed WebAssembly plugins add file types, previews (text, tree, table, image, 3D model), tool windows of their own (Tools menu), export and batch actions with access to the game's models and textures, and changes to game files through the `mods` folder (with undo), for every game. ✅ explorer (file list, preview, context menu, Settings → Plugins) and command line (`openrage plugin`), four example plugins included (OBJ export and import, a number and hash converter among them) · plugin packages (`.orp`) with install/uninstall in the explorer and the CLI · models into game formats (`build-model`) · 🔜 openFormats. [Writing plugins](https://two-play.github.io/openrage/plugins/)
+**Plugins** (API 0.3, preview): sandboxed WebAssembly plugins add file types, previews (text, tree, table, image, 3D model), tool windows of their own (Tools menu), export and batch actions with access to the game's models and textures, and changes to game files through the `mods` folder (with undo), for every game. ✅ explorer (file list, preview, context menu, Settings → Plugins) and command line (`openrage plugin`), four example plugins included (OBJ export and import, a number and hash converter among them) · plugin packages (`.orp`) with install/uninstall in the explorer and the CLI · models into game formats (`build-model`) · ✅ openFormats: OpenIV's text formats (`.odr`, `.oft`, `.odd`, `.otd` with `.mesh`, `.skel`, DDS) exported and imported back (preview). [Writing plugins](https://two-play.github.io/openrage/plugins/)
## Installation
Download the [latest release](https://github.com/Two-Play/openrage/releases/latest) for Linux (AppImage, Flatpak or `.tar.gz`) or Windows (`.zip`) and start `openrage-gui`. On first start it finds your game and sets up the keys. Step by step: **[Getting started](https://two-play.github.io/openrage/getting-started/)**.
+For the GTA VI preview, choose the folder containing `game_scarlett_master.exe` or RPF9 archives. With the supported executable beside the archives, OpenRAGE reads their tables of contents with the keys in it (the keys are not stored), so archives open at once. Names are matched to the hashes in the tables; files without a match are listed under `entries/`. Without the executable, or with another build, the explorer indexes the archives in the background and caches the results, which can take several minutes for large archives; recovered entries are then grouped by file type and offset, with model names recovered from their data where possible. Editing RPF9 archives is not supported.
+
+The CLI also supports browsing, extraction and verification, for example `openrage --game ls common.rpf` and `openrage --game verify common.rpf` (or a folder or file inside it). Running `verify` without a path checks all RPF9 archives below the game folder. Verification decodes the entries with checksum, size and bounds checks and returns an error on a failed entry; in the recovery view, unread data is outside its coverage. Nested archives are checked when their path is given. `verify --animations ` reads the clip dictionaries below a path, nested archives included; other format-specific verification and `--rebuild` are not supported for GTA VI yet.
+
To build from source (Rust, pinned in `rust-toolchain.toml`; on Linux also the fontconfig, xkbcommon, Wayland and ALSA development packages):
```sh
@@ -84,7 +93,7 @@ cargo build --release # target/release/openrage-gui and target/release/open
- [Explorer and search](https://two-play.github.io/openrage/guide/): the window, keyboard, search, settings
- [Viewing files](https://two-play.github.io/openrage/viewers/): what each format shows and exports
- [Modding](https://two-play.github.io/openrage/modding/): edit mode, editing archives, undo, `.oiv` packages, the `mods` folder
-- [GTA IV](https://two-play.github.io/openrage/gta-iv/) and [Red Dead Redemption 2](https://two-play.github.io/openrage/rdr2/): setup and what works per game
+- [GTA VI](https://two-play.github.io/openrage/gta-vi/), [GTA IV](https://two-play.github.io/openrage/gta-iv/) and [Red Dead Redemption 2](https://two-play.github.io/openrage/rdr2/): setup and what works per game
- [Command line](https://two-play.github.io/openrage/cli/): every `openrage` command
- [Writing plugins](https://two-play.github.io/openrage/plugins/): sandboxed WebAssembly plugins, SDK and API
- [Development](https://two-play.github.io/openrage/development/): building from source, build environment, releases, project layout
@@ -95,4 +104,4 @@ The website lives in [`site/`](site/) and is built from Markdown.
GPL-3.0-only, except `crates/rage-tfit2` (the RDR2 archive cipher, ported from an AGPL-3.0 project), which is AGPL-3.0-only, and the plugin interface and SDK (`crates/openrage-plugins/wit`, `plugins/`), which are MIT OR Apache-2.0 so that plugins may use any licence. See [LICENSE](LICENSE) and [NOTICE.md](NOTICE.md) for third-party attributions, and [THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md) for the licenses of all third-party crates in the programs (generated from `Cargo.lock`, checked in CI). The same is in the app under **Help → About OpenRAGE**, via `openrage licenses` and on the [licenses page](https://two-play.github.io/openrage/licenses/).
-Grand Theft Auto, Red Dead Redemption, RAGE and Rockstar Games are trademarks of Take-Two Interactive Software, Inc. The screenshots show OpenRAGE displaying files from the author's own copy of the game.
+Grand Theft Auto, Red Dead Redemption, RAGE and Rockstar Games are trademarks of Take-Two Interactive Software, Inc.
diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md
index 8dff725..65eecd2 100644
--- a/THIRD_PARTY_LICENSES.md
+++ b/THIRD_PARTY_LICENSES.md
@@ -3,7 +3,7 @@
OpenRAGE is licensed under the GPL-3.0-only (see `LICENSE`); `crates/rage-tfit2` under the
AGPL-3.0-only. Credits for format knowledge and ported code are in `NOTICE.md`.
-The OpenRAGE programs contain the following 546 Rust crates. Their license texts
+The OpenRAGE programs contain the following 547 Rust crates. Their license texts
follow, each with the crates it applies to.
This file is generated by `dev/third_party_licenses.py`; do not edit it by hand.
@@ -281,6 +281,7 @@ This file is generated by `dev/third_party_licenses.py`; do not edit it by hand.
| [once_cell_polyfill](https://github.com/polyfill-rs/once_cell_polyfill) | 1.70.2 | MIT OR Apache-2.0 |
| [oozextract](https://github.com/lvlvllvlvllvlvl/oozextract) | 0.5.7 | MIT |
| [option-ext](https://github.com/soc/option-ext.git) | 0.2.0 | MPL-2.0 |
+| [opus-rs](https://github.com/restsend/opus-rs) | 0.1.42 | BSD-3-Clause |
| [ordered-float](https://github.com/reem/rust-ordered-float) | 5.5.1 | MIT |
| [ordered-stream](https://github.com/danieldg/ordered-stream) | 0.2.0 | MIT OR Apache-2.0 |
| [os_pipe](https://github.com/oconnor663/os_pipe.rs) | 1.2.3 | MIT |
@@ -8365,6 +8366,60 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) #44
+Used by: opus-rs 0.1.42
+
+~~~~text
+
+Copyright 2026 restsend.com
+
+Copyright 2001-2023 Xiph.Org, Skype Limited, Octasic,
+ Jean-Marc Valin, Timothy B. Terriberry,
+ CSIRO, Gregory Maxwell, Mark Borgerding,
+ Erik de Castro Lopo, Mozilla, Amazon
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+- Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+- Neither the name of Internet Society, IETF or IETF Trust, nor the
+names of specific contributors, may be used to endorse or promote
+products derived from this software without specific prior written
+permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Opus is subject to the royalty-free patent licenses which are
+specified at:
+
+Xiph.Org Foundation:
+https://datatracker.ietf.org/ipr/1524/
+
+Microsoft Corporation:
+https://datatracker.ietf.org/ipr/1914/
+
+Broadcom Corporation:
+https://datatracker.ietf.org/ipr/1526/
+~~~~
+
+### BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) #45
+
Used by: encoding_rs 0.8.44
~~~~text
@@ -8424,7 +8479,7 @@ pub(crate) static GB18030_2022_OVERRIDE_BYTES: [[u8; 2]; 18] = [
];
~~~~
-### BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) #45
+### BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) #46
Used by: tiny-skia 0.11.4, tiny-skia 0.12.0, tiny-skia-path 0.11.4, tiny-skia-path 0.12.0
@@ -8461,7 +8516,7 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
~~~~
-### BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) #46
+### BSD 3-Clause "New" or "Revised" License (BSD-3-Clause) #47
Used by: encoding_rs 0.8.44
@@ -8494,7 +8549,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
~~~~
-### Boost Software License 1.0 (BSL-1.0) #47
+### Boost Software License 1.0 (BSL-1.0) #48
Used by: error-code 3.4.0
@@ -8524,7 +8579,7 @@ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### Boost Software License 1.0 (BSL-1.0) #48
+### Boost Software License 1.0 (BSL-1.0) #49
Used by: clipboard-win 5.4.3
@@ -8538,7 +8593,7 @@ The copyright notices in the Software and this entire statement, including the a
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### GNU General Public License v3.0 only (GPL-3.0-only) #49
+### GNU General Public License v3.0 only (GPL-3.0-only) #50
Used by: i-slint-backend-selector 1.18.1, i-slint-backend-winit 1.18.1, i-slint-common 1.18.1, i-slint-compiler 1.18.1, i-slint-core 1.18.1, i-slint-core-macros 1.18.1, i-slint-renderer-femtovg 1.18.1, i-slint-renderer-software 1.18.1, slint 1.18.1, slint-build 1.18.1, slint-macros 1.18.1
@@ -8777,7 +8832,7 @@ You should also get your employer (if you work as a programmer) or school, if an
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .
~~~~
-### ISC License (ISC) #50
+### ISC License (ISC) #51
Used by: libloading 0.8.9
@@ -8796,7 +8851,7 @@ NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE US
THIS SOFTWARE.
~~~~
-### MIT License (MIT) #51
+### MIT License (MIT) #52
Used by: uds_windows 1.2.1
@@ -8824,7 +8879,7 @@ Used by: uds_windows 1.2.1
SOFTWARE
~~~~
-### MIT License (MIT) #52
+### MIT License (MIT) #53
Used by: cfg_aliases 0.2.2
@@ -8857,7 +8912,7 @@ The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::tar
---
~~~~
-### MIT License (MIT) #53
+### MIT License (MIT) #54
Used by: texpresso 2.0.2
@@ -8924,7 +8979,7 @@ where
}
~~~~
-### MIT License (MIT) #54
+### MIT License (MIT) #55
Used by: mio 1.2.4
@@ -8950,7 +9005,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #55
+### MIT License (MIT) #56
Used by: libsqlite3-sys 0.39.1, rusqlite 0.41.1
@@ -8976,7 +9031,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #56
+### MIT License (MIT) #57
Used by: nom 8.0.0
@@ -9003,7 +9058,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #57
+### MIT License (MIT) #58
Used by: float-cmp 0.9.0
@@ -9029,7 +9084,7 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #58
+### MIT License (MIT) #59
Used by: wayland-backend 0.3.17, wayland-client 0.31.15, wayland-cursor 0.31.14, wayland-protocols 0.32.13, wayland-protocols-plasma 0.3.12, wayland-protocols-wlr 0.3.12, wayland-scanner 0.31.11, wayland-sys 0.31.11
@@ -9055,7 +9110,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #59
+### MIT License (MIT) #60
Used by: ordered-float 5.5.1
@@ -9087,7 +9142,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #60
+### MIT License (MIT) #61
Used by: dlib 0.5.3
@@ -9113,7 +9168,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #61
+### MIT License (MIT) #62
Used by: memoffset 0.9.1
@@ -9139,7 +9194,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #62
+### MIT License (MIT) #63
Used by: bytes 1.12.1
@@ -9171,7 +9226,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #63
+### MIT License (MIT) #64
Used by: smithay-client-toolkit 0.19.2
@@ -9197,7 +9252,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #64
+### MIT License (MIT) #65
Used by: calloop 0.13.0
@@ -9223,7 +9278,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #65
+### MIT License (MIT) #66
Used by: slab 0.4.12
@@ -9255,7 +9310,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #66
+### MIT License (MIT) #67
Used by: tracing 0.1.44, tracing-attributes 0.1.31, tracing-core 0.1.36
@@ -9287,7 +9342,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #67
+### MIT License (MIT) #68
Used by: pico-args 0.5.0
@@ -9313,7 +9368,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #68
+### MIT License (MIT) #69
Used by: pin-weak 1.1.0
@@ -9339,7 +9394,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #69
+### MIT License (MIT) #70
Used by: clru 0.6.3
@@ -9365,7 +9420,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #70
+### MIT License (MIT) #71
Used by: strict-num 0.1.1
@@ -9391,7 +9446,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #71
+### MIT License (MIT) #72
Used by: calloop-wayland-source 0.3.0
@@ -9417,7 +9472,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #72
+### MIT License (MIT) #73
Used by: wayland-csd-frame 0.3.0
@@ -9443,7 +9498,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #73
+### MIT License (MIT) #74
Used by: zbus 5.19.0, zbus_macros 5.19.0, zbus_names 4.3.5, zbus_xml 5.2.1, zvariant 5.15.1, zvariant_derive 5.15.1
@@ -9475,7 +9530,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #74
+### MIT License (MIT) #75
Used by: zcheapstr 1.2.0
@@ -9507,7 +9562,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #75
+### MIT License (MIT) #76
Used by: winresource 0.1.34
@@ -9539,7 +9594,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #76
+### MIT License (MIT) #77
Used by: synstructure 0.14.0
@@ -9553,7 +9608,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #77
+### MIT License (MIT) #78
Used by: wayland-protocols 0.32.13
@@ -9593,7 +9648,7 @@ The above is the version of the MIT "Expat" License used by X.org:
http://cgit.freedesktop.org/xorg/xserver/tree/COPYING
~~~~
-### MIT License (MIT) #78
+### MIT License (MIT) #79
Used by: glutin-winit 0.5.0
@@ -9619,7 +9674,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #79
+### MIT License (MIT) #80
Used by: texpresso 2.0.2
@@ -9648,7 +9703,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #80
+### MIT License (MIT) #81
Used by: tree_magic_mini 3.2.2
@@ -9676,7 +9731,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #81
+### MIT License (MIT) #82
Used by: imagesize 0.15.0
@@ -9704,7 +9759,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #82
+### MIT License (MIT) #83
Used by: alsa-sys 0.4.0
@@ -9732,7 +9787,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #83
+### MIT License (MIT) #84
Used by: rgb 0.8.53
@@ -9760,7 +9815,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #84
+### MIT License (MIT) #85
Used by: strum 0.28.0, strum_macros 0.28.0
@@ -9788,7 +9843,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #85
+### MIT License (MIT) #86
Used by: ashpd 0.11.1
@@ -9816,7 +9871,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #86
+### MIT License (MIT) #87
Used by: cfg_aliases 0.2.2
@@ -9832,7 +9887,7 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #87
+### MIT License (MIT) #88
Used by: xcursor 0.3.11
@@ -9860,7 +9915,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #88
+### MIT License (MIT) #89
Used by: rfd 0.15.4, sctk-adwaita 0.10.1
@@ -9888,7 +9943,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #89
+### MIT License (MIT) #90
Used by: convert_case 0.10.0
@@ -9916,7 +9971,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #90
+### MIT License (MIT) #91
Used by: dpi 0.1.2, libm 0.2.16, oozextract 0.5.7, rspolib 0.1.2, taffy 0.10.1
@@ -9941,7 +9996,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTI
USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #91
+### MIT License (MIT) #92
Used by: tokio 1.54.1
@@ -9969,7 +10024,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #92
+### MIT License (MIT) #93
Used by: simd-adler32 0.3.10
@@ -9997,7 +10052,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #93
+### MIT License (MIT) #94
Used by: wayland-protocols-plasma 0.3.12
@@ -10023,7 +10078,7 @@ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #94
+### MIT License (MIT) #95
Used by: endi 1.1.1, x11-dl 2.21.0, zbus-lockstep 0.5.2, zbus-lockstep-macros 0.5.2, zmij 1.0.23, zvariant_utils 4.2.0
@@ -10053,7 +10108,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #95
+### MIT License (MIT) #96
Used by: winnow 1.0.5
@@ -10078,7 +10133,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #96
+### MIT License (MIT) #97
Used by: pulldown-cmark 0.13.6
@@ -10106,7 +10161,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #97
+### MIT License (MIT) #98
Used by: tracing-core 0.1.36, zip 9.5.0
@@ -10134,7 +10189,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #98
+### MIT License (MIT) #99
Used by: xml-rs 0.8.29
@@ -10162,7 +10217,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #99
+### MIT License (MIT) #100
Used by: natord 1.0.9
@@ -10190,7 +10245,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #100
+### MIT License (MIT) #101
Used by: phf 0.13.1, phf_generator 0.13.1, phf_macros 0.13.1, phf_shared 0.13.1
@@ -10217,7 +10272,7 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
~~~~
-### MIT License (MIT) #101
+### MIT License (MIT) #102
Used by: byteorder 1.5.0, byteorder-lite 0.1.0, memchr 2.8.3, termcolor 1.4.1
@@ -10245,7 +10300,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #102
+### MIT License (MIT) #103
Used by: strsim 0.11.1
@@ -10275,7 +10330,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #103
+### MIT License (MIT) #104
Used by: derive_more 2.1.1, derive_more-impl 2.1.1
@@ -10303,7 +10358,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #104
+### MIT License (MIT) #105
Used by: color_quant 1.1.0
@@ -10331,7 +10386,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #105
+### MIT License (MIT) #106
Used by: winapi-util 0.1.11
@@ -10359,7 +10414,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #106
+### MIT License (MIT) #107
Used by: xmlwriter 0.1.0
@@ -10387,7 +10442,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #107
+### MIT License (MIT) #108
Used by: fontdb 0.24.0
@@ -10415,7 +10470,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #108
+### MIT License (MIT) #109
Used by: xkbcommon-dl 0.4.2
@@ -10443,7 +10498,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #109
+### MIT License (MIT) #110
Used by: harfrust 0.12.0
@@ -10472,7 +10527,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #110
+### MIT License (MIT) #111
Used by: yeslogic-fontconfig-sys 6.0.1
@@ -10503,7 +10558,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #111
+### MIT License (MIT) #112
Used by: os_pipe 1.2.3
@@ -10529,7 +10584,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #112
+### MIT License (MIT) #113
Used by: generic-array 0.14.7
@@ -10557,7 +10612,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
~~~~
-### MIT License (MIT) #113
+### MIT License (MIT) #114
Used by: quick-xml 0.41.0
@@ -10587,7 +10642,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### MIT License (MIT) #114
+### MIT License (MIT) #115
Used by: urlencoding 2.1.3
@@ -10614,7 +10669,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
~~~~
-### Mozilla Public License 2.0 (MPL-2.0) #115
+### Mozilla Public License 2.0 (MPL-2.0) #116
Used by: symphonia 0.6.1, symphonia-bundle-mp3 0.6.1, symphonia-core 0.6.1, symphonia-metadata 0.6.1
@@ -10994,7 +11049,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice
defined by the Mozilla Public License, v. 2.0.
~~~~
-### Mozilla Public License 2.0 (MPL-2.0) #116
+### Mozilla Public License 2.0 (MPL-2.0) #117
Used by: option-ext 0.2.0
@@ -11374,7 +11429,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice
defined by the Mozilla Public License, v. 2.0.
~~~~
-### Unicode License v3 (Unicode-3.0) #117
+### Unicode License v3 (Unicode-3.0) #118
Used by: unicode-ident 1.0.27
@@ -11420,7 +11475,7 @@ dealings in these Data Files or Software without prior written
authorization of the copyright holder.
~~~~
-### Unicode License v3 (Unicode-3.0) #118
+### Unicode License v3 (Unicode-3.0) #119
Used by: fixed_decimal 0.7.3, icu_collections 2.4.0, icu_decimal 2.4.0, icu_decimal_data 2.4.0, icu_locale_core 2.4.0, icu_locale_fallback 2.4.0, icu_locale_fallback_data 2.4.0, icu_normalizer 2.4.0, icu_normalizer_data 2.4.0, icu_properties 2.4.0, icu_properties_data 2.4.0, icu_provider 2.4.0, icu_segmenter 2.4.0, icu_segmenter_data 2.4.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.5, writeable 0.6.4, yoke 0.8.4, yoke-derive 0.8.4, zerofrom 0.1.8, zerofrom-derive 0.1.8, zerotrie 0.2.5, zerovec 0.11.9, zerovec-derive 0.11.7
@@ -11473,7 +11528,7 @@ Portions of ICU4X may have been adapted from ICU4C and/or ICU4J.
ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others.
~~~~
-### zlib License (Zlib) #119
+### zlib License (Zlib) #120
Used by: slotmap 1.1.1
@@ -11499,7 +11554,7 @@ the following restrictions:
3. This notice may not be removed or altered from any source distribution.
~~~~
-### zlib License (Zlib) #120
+### zlib License (Zlib) #121
Used by: foldhash 0.1.5, foldhash 0.2.0
diff --git a/crates/openrage-app/Cargo.toml b/crates/openrage-app/Cargo.toml
index 3a3572c..c4a724f 100644
--- a/crates/openrage-app/Cargo.toml
+++ b/crates/openrage-app/Cargo.toml
@@ -24,4 +24,5 @@ png = "0.18"
zip.workspace = true
[dev-dependencies]
+flate2.workspace = true
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
diff --git a/crates/openrage-app/src/anim.rs b/crates/openrage-app/src/anim.rs
index a737cd6..94f4f54 100644
--- a/crates/openrage-app/src/anim.rs
+++ b/crates/openrage-app/src/anim.rs
@@ -6,7 +6,7 @@ use rage_formats::math::{self, Mat4};
use crate::expr::Local;
-/// Reads a clip dictionary (`.ycd`, GTA V or RDR2; GTA IV `.wad`) or a cutscene's
+/// Reads a clip dictionary (`.ycd`, GTA V or RDR2; GTA IV `.wad`; GTA VI `.#cd`) or a cutscene's
/// animation (`.cut`, its sections joined), mods included.
pub fn load_clips(
game_dir: &std::path::Path,
@@ -25,6 +25,10 @@ pub fn load_clips(
rpf.entries().and_then(|e| e.get(i)).ok_or_else(|| anyhow::anyhow!("archive table not readable"))?;
Ok(rage_formats::clip::parse_ycd(&rpf.read_resource(entry)?)?)
}
+ Node::Rpf9File(rpf, i) => {
+ let (system, graphics) = crate::rpf9::resource(&rpf, i)?;
+ Ok(rage_formats::clip6::parse(&rage_resource::Resource { version: 0, system, graphics })?)
+ }
_ => anyhow::bail!("{vpath} is not a file inside an archive"),
}
}
@@ -88,7 +92,8 @@ impl Binding {
pub fn new(skeleton: &Skeleton, animation: &Animation) -> Self {
let mut tracks = vec![[None; 3]; skeleton.bones.len()];
for (i, t) in animation.tracks.iter().enumerate() {
- let Some(b) = skeleton.find_tag(t.bone) else { continue };
+ let found = if t.bone_hash != 0 { skeleton.find_hash(t.bone_hash) } else { skeleton.find_tag(t.bone) };
+ let Some(b) = found else { continue };
let slot = match t.track {
TRACK_BONE_TRANSLATION => 0,
TRACK_BONE_ROTATION => 1,
@@ -224,7 +229,7 @@ mod tests {
let animation = Animation::from_frames(
1,
0.0,
- vec![BoneTrack { bone: 1, format: 1, track: TRACK_BONE_ROTATION }],
+ vec![BoneTrack { bone: 1, format: 1, track: TRACK_BONE_ROTATION, ..Default::default() }],
vec![vec![[0.0, 0.0, h, h]]],
);
let binding = Binding::new(&skeleton, &animation);
diff --git a/crates/openrage-app/src/audio.rs b/crates/openrage-app/src/audio.rs
index 8870310..a93952e 100644
--- a/crates/openrage-app/src/audio.rs
+++ b/crates/openrage-app/src/audio.rs
@@ -18,6 +18,7 @@ pub fn load(game_dir: &Path, keys: Option>, vpath: &str) -> Result
let data = match node {
Node::ArchiveFile(rpf, id) => rpf.read(id)?,
Node::PlainFile(p) => std::fs::read(p)?,
+ Node::Rpf9File(rpf, i) => rpf.read_at(i)?,
_ => bail!("{vpath} is not a file"),
};
parse(data, keys.as_deref())
diff --git a/crates/openrage-app/src/detect.rs b/crates/openrage-app/src/detect.rs
index 5f532e1..a537650 100644
--- a/crates/openrage-app/src/detect.rs
+++ b/crates/openrage-app/src/detect.rs
@@ -74,12 +74,39 @@ pub fn is_rdr2_dir(dir: &Path) -> bool {
dir.join(RDR2_EXE).is_file()
}
+/// The program in the GTA VI Scarlett build.
+pub const GTA6_EXE: &str = "game_scarlett_master.exe";
+
+/// Whether a folder holds GTA VI: its Scarlett executable or archives in the
+/// RPF9 format. Archives can also be explored without the executable through
+/// the recovery view (see [`rage_rpf::rpf9`]).
+pub fn is_gta6_dir(dir: &Path) -> bool {
+ if is_gta5_dir(dir) || is_rdr2_dir(dir) || crate::gta4::is_gta4_dir(dir) {
+ return false;
+ }
+ if dir.join(GTA6_EXE).is_file() || rage_rpf::Rpf9::file_is_rpf9(&dir.join("common.rpf")) {
+ return true;
+ }
+ let Ok(rd) = fs::read_dir(dir) else { return false };
+ rd.flatten()
+ .map(|e| e.path())
+ .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("rpf")))
+ .any(|p| rage_rpf::Rpf9::file_is_rpf9(&p))
+}
+
+/// Whether a folder holds a game OpenRAGE can open.
+pub fn is_game_dir(dir: &Path) -> bool {
+ is_gta5_dir(dir) || is_rdr2_dir(dir) || crate::gta4::is_gta4_dir(dir) || is_gta6_dir(dir)
+}
+
/// The icon of the game in `dir`, from its own program: (width, height, RGBA).
pub fn game_icon(dir: &Path) -> Option<(u32, u32, Vec)> {
let programs: &[&str] = if is_rdr2_dir(dir) {
&[RDR2_EXE]
} else if crate::gta4::is_gta4_dir(dir) {
&["GTAIV.exe"]
+ } else if is_gta6_dir(dir) {
+ &[GTA6_EXE]
} else {
&["GTA5_Enhanced.exe", "GTA5.exe", "PlayGTAV.exe"]
};
@@ -87,7 +114,7 @@ pub fn game_icon(dir: &Path) -> Option<(u32, u32, Vec)> {
}
/// Short name of the game installed in `dir`: "GTA V Enhanced", "GTA V",
-/// "GTA IV", "RDR2", or `None` when no known executable is there.
+/// "GTA IV", "RDR2", "GTA VI", or `None` when the folder holds no known game.
pub fn game_name(dir: &Path) -> Option<&'static str> {
if is_rdr2_dir(dir) {
Some("RDR2")
@@ -97,6 +124,8 @@ pub fn game_name(dir: &Path) -> Option<&'static str> {
Some("GTA V")
} else if crate::gta4::is_gta4_dir(dir) {
Some("GTA IV")
+ } else if is_gta6_dir(dir) {
+ Some("GTA VI")
} else {
None
}
@@ -130,6 +159,35 @@ pub fn collect_rpfs(dir: &Path, out: &mut Vec) {
mod tests {
use super::*;
+ #[test]
+ fn detects_gta6_from_scarlett_executable_or_rpf9_archives() {
+ let dir = std::env::temp_dir().join(format!("openrage-detect-gta6-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&dir).unwrap();
+ assert!(!is_game_dir(&dir));
+
+ // The executable identifies the game even before archives are copied.
+ fs::write(dir.join(GTA6_EXE), b"MZ").unwrap();
+ assert!(is_gta6_dir(&dir));
+ assert!(is_game_dir(&dir));
+ assert_eq!(game_name(&dir), Some("GTA VI"));
+ fs::remove_file(dir.join(GTA6_EXE)).unwrap();
+
+ // Archive-only copies remain supported. A non-RPF9 common.rpf must
+ // not hide another archive with the RPF9 signature.
+ fs::write(dir.join("common.rpf"), b"unrelated data").unwrap();
+ assert!(!is_gta6_dir(&dir));
+ fs::write(dir.join("data.RPF"), b"9FPR").unwrap();
+ assert!(is_gta6_dir(&dir));
+ assert_eq!(game_name(&dir), Some("GTA VI"));
+
+ // An RPF9 file copied into another game's folder does not switch it.
+ fs::write(dir.join("GTA5.exe"), b"MZ").unwrap();
+ assert!(!is_gta6_dir(&dir));
+ assert_eq!(game_name(&dir), Some("GTA V"));
+ fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn parses_library_folders() {
let vdf = r#"
diff --git a/crates/openrage-app/src/extract.rs b/crates/openrage-app/src/extract.rs
index 1299686..463e754 100644
--- a/crates/openrage-app/src/extract.rs
+++ b/crates/openrage-app/src/extract.rs
@@ -42,7 +42,10 @@ pub fn extract_rpf8(
if let Some(parent) = target.parent() {
fs::create_dir_all(parent)?;
}
- match rpf.read(&rpf.entries().expect("entries")[i]) {
+ let entry = &rpf.entries().expect("entries")[i];
+ // Resources as RSC8 files (header and pages), so they can be put back.
+ let data = if entry.is_resource { rpf.resource_file(entry) } else { rpf.read(entry) };
+ match data {
Ok(data) => {
fs::write(&target, &data)?;
s.files += 1;
diff --git a/crates/openrage-app/src/gta4_cutscene.rs b/crates/openrage-app/src/gta4_cutscene.rs
index 7d350bd..0f3b674 100644
--- a/crates/openrage-app/src/gta4_cutscene.rs
+++ b/crates/openrage-app/src/gta4_cutscene.rs
@@ -1451,7 +1451,7 @@ FX_CS_spit:effect1_0 0 1205 500 500 0 0 0 0 0 0 0\n[/EFFECTS]\n[DURATION]\n2000\
#[test]
fn props_move_by_their_root() {
use rage_formats::clip::BoneTrack;
- let track = |bone, track, format| BoneTrack { bone, format, track };
+ let track = |bone, track, format| BoneTrack { bone, format, track, ..Default::default() };
let body = Animation::from_frames(
2,
1.0,
diff --git a/crates/openrage-app/src/gta6_models.rs b/crates/openrage-app/src/gta6_models.rs
new file mode 100644
index 0000000..7f654a6
--- /dev/null
+++ b/crates/openrage-app/src/gta6_models.rs
@@ -0,0 +1,322 @@
+//! GTA VI models.
+//!
+//! A model is stored as its system part and then its graphics part. The
+//! archive's table says how long they are. In the recovery view both are cut into zlib streams of 64 KiB. Without the table of contents nothing
+//! says where one part ends: the recovery view lists a resource as its first
+//! entry (which starts the system part) and what follows it. So the parts
+//! are found by trying: every cut between two streams is a possible end of
+//! the system part, and the reader says whether the graphics part reaches
+//! far enough.
+
+use std::collections::HashSet;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+
+use anyhow::{Context, Result, bail};
+use rage_formats::drawable::{Bone, Drawable, Skeleton};
+use rage_formats::drawable6::{self, ModelError};
+use rage_formats::math;
+use rage_rpf::Rpf9;
+
+/// Streams unpack to this many bytes, the last one of a part to fewer.
+const STREAM: usize = 0x10000;
+/// A system part is at most this long.
+const MAX_SYSTEM: usize = 32 << 20;
+/// A resource is at most this long, and spread over at most this many entries.
+const MAX_RESOURCE: usize = 256 << 20;
+const MAX_ENTRIES: usize = 4096;
+
+/// Reads the model that starts at entry `index`: its drawables with their names.
+pub fn load(rpf: &Rpf9, index: usize) -> Result> {
+ let entries = rpf.entries()?;
+ let first = entries.get(index).context("no such entry")?;
+ let mut data = rpf.read(first)?;
+ if drawable6::root(&data).is_none() {
+ bail!("this resource is not a model");
+ }
+ if let Some((system, _)) = rpf.resource_parts(first) {
+ let (system, graphics) = data.split_at_checked(system as usize).context("the resource is cut off")?;
+ return Ok(named(drawable6::parse(system, graphics)?));
+ }
+ // Where streams end: the possible ends of the system part.
+ let mut cuts: Vec = (1..=data.len().div_ceil(STREAM)).map(|i| (i * STREAM).min(data.len())).collect();
+ let mut last = index;
+ loop {
+ let mut needs_more = false;
+ let mut failure = None;
+ for cut in cuts.iter().copied().take_while(|c| *c <= MAX_SYSTEM) {
+ match drawable6::parse(&data[..cut], &data[cut..]) {
+ Ok(drawables) => return Ok(named(drawables)),
+ Err(ModelError::Graphics(_)) => needs_more = true,
+ Err(e) => failure = failure.or(Some(e)),
+ }
+ }
+ // The graphics part goes on in the next entry.
+ if !needs_more || !Rpf9::follows(&entries, last) || last - index >= MAX_ENTRIES || data.len() >= MAX_RESOURCE {
+ match failure {
+ Some(e) if !needs_more => bail!(e),
+ _ => bail!("the model's vertex and index data was not found after it"),
+ }
+ }
+ last += 1;
+ let more = rpf.read(&entries[last])?;
+ let start = data.len();
+ data.extend_from_slice(&more);
+ cuts.extend((1..=more.len().div_ceil(STREAM)).map(|i| start + (i * STREAM).min(more.len())));
+ }
+}
+
+fn named(drawables: Vec) -> Vec<(String, Drawable)> {
+ drawables
+ .into_iter()
+ .enumerate()
+ .map(|(i, d)| (if d.name.is_empty() { format!("drawable {i}") } else { d.name.clone() }, d))
+ .collect()
+}
+
+/// The archive with the skeletons people and animals are put together on.
+const BASE_SKELETONS: &str = "packs.rpf/packs/base/models/metaped_fragments.rpf";
+
+/// A vertex with less weight than this on known bones moves with the nearest.
+const MIN_WEIGHT: f32 = 0.3;
+
+type Skeletons = Arc>;
+
+/// The base skeletons of the game with their file names (read once).
+fn base_skeletons(game: &Path) -> Skeletons {
+ static CACHE: Mutex> = Mutex::new(None);
+ let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((of, found)) = &*cache
+ && of == game
+ {
+ return Arc::clone(found);
+ }
+ let found = Arc::new(rage_rpf::in_own_threads(|| read_base_skeletons(game)).unwrap_or_default());
+ *cache = Some((game.to_path_buf(), Arc::clone(&found)));
+ found
+}
+
+fn read_base_skeletons(game: &Path) -> Result> {
+ use rayon::prelude::*;
+ let (node, _) = rage_mods::resolve(game, BASE_SKELETONS, None)?;
+ let rage_rpf::vfs::Node::Rpf9Dir(rpf, _) = node else { bail!("no archive") };
+ let entries = rpf.entries()?;
+ let mut found: Vec<(String, Skeleton)> = (0..entries.len())
+ .into_par_iter()
+ .filter_map(|i| {
+ let name = rpf.entry_name(&entries[i]).to_ascii_lowercase();
+ let (system, graphics) = crate::rpf9::resource(&rpf, i).ok()?;
+ let skeleton = drawable6::parse(&system, &graphics).ok()?.into_iter().next()?.skeleton?;
+ Some((name.rsplit('/').next().unwrap_or(&name).to_owned(), skeleton))
+ })
+ .collect();
+ found.sort_by(|a, b| a.0.cmp(&b.0));
+ Ok(found)
+}
+
+/// Binds meshes that name bones of another skeleton (parts of people and
+/// animals) to it, and gives that skeleton. `None` if there are none, or the
+/// game has no skeleton for them.
+pub(crate) fn bind(game: &Path, file: &str, drawables: &mut [(String, Drawable)]) -> Option {
+ let wanted: HashSet =
+ drawables.iter().flat_map(|(_, d)| &d.meshes).flat_map(|m| &m.bone_hashes).copied().collect();
+ if wanted.is_empty() {
+ return None;
+ }
+ let bases = base_skeletons(game);
+ let mut skeleton = best_base(&bases, file, &wanted)?.clone();
+ bind_to(&mut skeleton, drawables);
+ Some(skeleton)
+}
+
+/// The skeleton with the most of the bones; of several with as many, the one
+/// whose name is most like the file's. `None` if none has any of them, and
+/// the file's name does not tell either.
+fn best_base<'a>(bases: &'a [(String, Skeleton)], file: &str, wanted: &HashSet) -> Option<&'a Skeleton> {
+ let file = file.to_ascii_lowercase();
+ let words: Vec<&str> = file.split(['_', '.', '+']).collect();
+ // `fr1`, `mo1`, …: a woman's or a man's part, of one of the builds.
+ let sex = words.iter().find_map(|w| match w.as_bytes() {
+ [b'f', b'a'..=b'z', b'0'..=b'9'] => Some("ambient_femalebody.#ft"),
+ [b'm', b'a'..=b'z', b'0'..=b'9'] => Some("ambient_malebody.#ft"),
+ _ => None,
+ });
+ let rated = bases.iter().filter_map(|(name, skeleton)| {
+ let own: HashSet = skeleton.bones.iter().map(|b| rage_core::hash::joaat(&b.name)).collect();
+ let has = wanted.iter().filter(|h| own.contains(h)).count();
+ let alike = words.iter().filter(|w| w.len() > 2 && name.contains(**w)).count();
+ (has > 0 || sex == Some(name)).then_some(((has, sex == Some(name), alike), skeleton))
+ });
+ // The first one of the best.
+ rated.reduce(|best, next| if next.0 > best.0 { next } else { best }).map(|(_, s)| s)
+}
+
+/// Binds the meshes to the skeleton, which gets the bones it lacks from the
+/// drawables' own (hair, garments).
+fn bind_to(skeleton: &mut Skeleton, drawables: &mut [(String, Drawable)]) {
+ let places =
+ |s: &Skeleton| -> Vec<[f32; 3]> { s.world_transforms().iter().map(|m| [m[12], m[13], m[14]]).collect() };
+ // The main bones of the body, with their places.
+ let body: Vec<(usize, [f32; 3])> = places(skeleton)
+ .into_iter()
+ .enumerate()
+ .filter(|(i, _)| skeleton.bones[*i].name.starts_with("SKEL_"))
+ .collect();
+ let nearest = |at: &[f32; 3]| -> Option {
+ let far = |p: &[f32; 3]| (0..3).map(|k| (p[k] - at[k]).powi(2)).sum::();
+ body.iter().min_by(|a, b| far(&a.1).total_cmp(&far(&b.1))).map(|(i, _)| *i)
+ };
+ // Where the bones of each drawable's own skeleton are.
+ let mut of_own: Vec> = Vec::new();
+ for (_, d) in drawables.iter() {
+ let Some(own) = &d.skeleton else {
+ of_own.push(Vec::new());
+ continue;
+ };
+ let at = places(own);
+ let mut placed: Vec = Vec::with_capacity(own.bones.len());
+ for (i, b) in own.bones.iter().enumerate() {
+ if let Some(there) = skeleton.find_hash(rage_core::hash::joaat(&b.name)) {
+ placed.push(there as i16);
+ continue;
+ }
+ let mut bone = b.clone();
+ bone.parent = match usize::try_from(b.parent).ok().and_then(|p| placed.get(p)) {
+ Some(&p) => p,
+ // Loose: it hangs from the nearest bone of the body.
+ None => {
+ let Some(nearest) = nearest(&at[i]) else {
+ placed.push(0);
+ continue;
+ };
+ attach(&mut bone, skeleton, nearest);
+ nearest as i16
+ }
+ };
+ placed.push(skeleton.bones.len() as i16);
+ skeleton.bones.push(bone);
+ }
+ of_own.push(placed);
+ }
+ for (k, (_, d)) in drawables.iter_mut().enumerate() {
+ for mesh in &mut d.meshes {
+ if mesh.bone_hashes.is_empty() {
+ // Bound to the drawable's own skeleton.
+ let own = &of_own[k];
+ let there = |b: u16| own.get(usize::from(b)).map_or(b, |&b| b as u16);
+ mesh.bone_indices.iter_mut().flatten().for_each(|b| *b = there(*b));
+ continue;
+ }
+ let map: Vec> =
+ mesh.bone_hashes.iter().map(|&h| skeleton.find_hash(h).map(|b| b as u16)).collect();
+ mesh.bone_hashes.clear();
+ let vertices = mesh.positions.iter().zip(mesh.bone_indices.iter_mut().zip(&mut mesh.bone_weights));
+ for (position, (bones, weights)) in vertices {
+ // Bones of yet another skeleton do not count.
+ for (b, w) in bones.iter_mut().zip(weights.iter_mut()) {
+ match map.get(usize::from(*b)).copied().flatten() {
+ Some(there) => *b = there,
+ None => (*b, *w) = (0, 0.0),
+ }
+ }
+ let total: f32 = weights.iter().sum();
+ if total > MIN_WEIGHT {
+ weights.iter_mut().for_each(|w| *w /= total);
+ } else {
+ *bones = [nearest(position).unwrap_or(0) as u16, 0, 0, 0];
+ *weights = [1.0, 0.0, 0.0, 0.0];
+ }
+ }
+ }
+ }
+}
+
+/// Moves a bone without a parent under one of the skeleton's, where it stays.
+fn attach(bone: &mut Bone, skeleton: &Skeleton, parent: usize) {
+ let inverse = math::inverse_affine(&skeleton.world_transforms()[parent]);
+ bone.translation = math::transform_point(&inverse, bone.translation);
+ let (mut turn, mut at) = ([0.0, 0.0, 0.0, 1.0], Some(parent));
+ while let Some(b) = at.and_then(|i| skeleton.bones.get(i)) {
+ turn = turned(b.rotation, turn);
+ at = usize::try_from(b.parent).ok();
+ }
+ let back = [-turn[0], -turn[1], -turn[2], turn[3]];
+ bone.rotation = turned(back, bone.rotation);
+}
+
+/// The rotation `b`, then `a`.
+fn turned(a: [f32; 4], b: [f32; 4]) -> [f32; 4] {
+ let ([ax, ay, az, aw], [bx, by, bz, bw]) = (a, b);
+ [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rage_core::hash::joaat;
+ use rage_formats::drawable::Mesh;
+
+ fn bone(name: &str, parent: i16, translation: [f32; 3], rotation: [f32; 4]) -> Bone {
+ Bone { name: name.into(), tag: 0, parent, translation, rotation, scale: [1.0; 3] }
+ }
+
+ fn body() -> Skeleton {
+ let half = std::f32::consts::FRAC_1_SQRT_2;
+ Skeleton {
+ bones: vec![
+ bone("SKEL_ROOT", -1, [0.0, 0.0, 1.0], [0.0, 0.0, half, half]),
+ bone("SKEL_Head", 0, [0.0, 0.0, 0.7], [half, 0.0, 0.0, half]),
+ ],
+ }
+ }
+
+ #[test]
+ fn parts_find_their_bones_by_name() {
+ let mesh = Mesh {
+ positions: vec![[0.0; 3], [0.0, 0.0, 1.8]],
+ bone_indices: vec![[0, 1, 2, 9], [2, 0, 0, 0]],
+ bone_weights: vec![[0.25, 0.25, 0.5, 0.0], [1.0, 0.0, 0.0, 0.0]],
+ bone_hashes: vec![joaat("GM_Collar"), joaat("SKEL_ROOT"), joaat("unknown")],
+ ..Default::default()
+ };
+ let own = Skeleton { bones: vec![bone("GM_Collar", -1, [0.1, 0.2, 1.6], [0.0, 0.0, 0.0, 1.0])] };
+ let mut drawables =
+ vec![("part".into(), Drawable { meshes: vec![mesh], skeleton: Some(own), ..Default::default() })];
+ let mut skeleton = body();
+ bind_to(&mut skeleton, &mut drawables);
+ // Unknown bones do not count; what has no others moves with the nearest.
+ let mesh = &drawables[0].1.meshes[0];
+ assert_eq!(mesh.bone_indices, [[2, 0, 0, 0], [1, 0, 0, 0]]);
+ assert_eq!(mesh.bone_weights, [[0.5, 0.5, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]]);
+ // The garment's bone stays where it was.
+ assert_eq!(skeleton.bones[2].parent, 1);
+ let world = skeleton.world_transforms()[2];
+ let expected = math::from_trs([0.1, 0.2, 1.6], [0.0, 0.0, 0.0, 1.0], [1.0; 3]);
+ assert!(world.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-5), "{world:?}");
+ }
+
+ #[test]
+ fn the_skeleton_is_the_one_with_the_bones() {
+ let dog = Skeleton { bones: vec![bone("SKEL_Tail", -1, [0.0; 3], [0.0, 0.0, 0.0, 1.0])] };
+ let bases = [
+ ("ambient_femalebody.#ft".to_owned(), body()),
+ ("ambient_malebody.#ft".to_owned(), body()),
+ ("crm_dog_00.#ft".to_owned(), dog),
+ ];
+ let pick = |file: &str, bones: &[&str]| {
+ let found = best_base(&bases, file, &bones.iter().map(|b| joaat(b)).collect());
+ found.and_then(|s| bases.iter().position(|(_, b)| std::ptr::eq(b, s)))
+ };
+ assert_eq!(pick("shirt_mr1_000.#dd", &["SKEL_Head"]), Some(1));
+ assert_eq!(pick("shirt_fr1_000.#dd", &["SKEL_Head"]), Some(0));
+ assert_eq!(pick("fur.#dd", &["SKEL_Tail"]), Some(2));
+ assert_eq!(pick("fur.#dd", &["a", "b", "SKEL_Tail"]), Some(2));
+ assert_eq!(pick("fur.#dd", &["a"]), None);
+ assert_eq!(pick("belt_fr1_000.#dd", &["a"]), Some(0));
+ }
+}
diff --git a/crates/openrage-app/src/gta6_textures.rs b/crates/openrage-app/src/gta6_textures.rs
new file mode 100644
index 0000000..926aad5
--- /dev/null
+++ b/crates/openrage-app/src/gta6_textures.rs
@@ -0,0 +1,170 @@
+//! GTA VI: the textures of models, which are in the texture pools.
+//!
+//! A model's shader names a texture by a 64-bit key; each texture pool
+//! (`.ttpf`, see [`rage_formats::ttpf`]) lists the keys of its textures. So
+//! the pools of a game are read once into a catalog of key → pool and number.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+
+use rage_formats::drawable::Drawable;
+use rage_formats::drawable::param::{BUMP_TEX, DIFFUSE_TEX, DIFFUSE_TEX2, LAYER_1_TEX, SPECULAR_TEX};
+use rage_formats::drawable6::texture_name;
+use rage_formats::texture::Texture;
+use rage_formats::ttpf::Pool;
+use rage_formats::ytd::{Layout, TextureDictionary};
+
+/// Textures on a model are read at most this many pixels wide and high.
+const MAX_SIDE: u32 = 1024;
+/// A model gets at most this many textures.
+const MAX_TEXTURES: usize = 64;
+
+/// Where the textures of a game are: per key, the pool and the number in it.
+#[derive(Default)]
+pub struct Catalog {
+ pools: Vec<(PathBuf, Pool)>,
+ by_key: HashMap,
+}
+
+impl Catalog {
+ /// Reads the tables of all texture pools below `game_dir`.
+ fn build(game_dir: &Path) -> Catalog {
+ let mut files = Vec::new();
+ crate::detect::collect_archives(game_dir, &["ttpf"], &mut files);
+ let mut catalog = Catalog::default();
+ for file in files {
+ let Ok(pool) = Pool::open(&file) else { continue };
+ for (number, key) in pool.keys().iter().enumerate().filter(|(_, key)| **key != 0) {
+ // The same texture can be in several pools: the first one that has data wins.
+ let has_data = pool.descriptor(number).is_some_and(|d| d.base.is_some());
+ let known = catalog
+ .by_key
+ .get(key)
+ .is_some_and(|(p, n)| catalog.pools[*p].1.descriptor(*n).is_some_and(|d| d.base.is_some()));
+ if !known && (has_data || !catalog.by_key.contains_key(key)) {
+ catalog.by_key.insert(*key, (catalog.pools.len(), number));
+ }
+ }
+ catalog.pools.push((file, pool));
+ }
+ catalog
+ }
+
+ pub fn len(&self) -> usize {
+ self.by_key.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.by_key.is_empty()
+ }
+
+ /// The texture with this key, with mip levels, the same for all that use
+ /// it at the time.
+ pub fn shared(&self, key: u64, side: u32) -> Option> {
+ type Known = HashMap<(u64, u32), Weak>;
+ static KNOWN: OnceLock> = OnceLock::new();
+ let lock = || KNOWN.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(known) = lock().get(&(key, side)).and_then(Weak::upgrade) {
+ return Some(known);
+ }
+ let (pool, number) = *self.by_key.get(&key)?;
+ let mut texture = self.pools[pool].1.texture_with_mips(number, Some(side)).ok()?;
+ texture.name = texture_name(key);
+ let mut known = lock();
+ // Another thread may have been quicker.
+ if let Some(theirs) = known.get(&(key, side)).and_then(Weak::upgrade) {
+ return Some(theirs);
+ }
+ let texture = Arc::new(texture);
+ if known.len().is_power_of_two() {
+ known.retain(|_, t| t.strong_count() > 0);
+ }
+ known.insert((key, side), Arc::downgrade(&texture));
+ Some(texture)
+ }
+
+ /// The texture with this key, named by the key.
+ pub fn texture(&self, key: u64) -> Option {
+ let (pool, number) = *self.by_key.get(&key)?;
+ let mut texture = self.pools[pool].1.texture(number, Some(MAX_SIDE)).ok()?;
+ texture.name = texture_name(key);
+ Some(texture)
+ }
+}
+
+/// The catalog of a game's texture pools; read on first use and kept.
+pub fn catalog(game_dir: &Path) -> Arc {
+ static CATALOGS: OnceLock>>> = OnceLock::new();
+ let mut catalogs = CATALOGS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
+ Arc::clone(
+ catalogs
+ .entry(game_dir.to_path_buf())
+ .or_insert_with(|| Arc::new(rage_rpf::in_own_threads(|| Catalog::build(game_dir)))),
+ )
+}
+
+/// The names of the textures of shaders, of these kinds.
+fn names<'a>(drawables: &'a [(String, Drawable)], wanted: &[u32]) -> Vec<&'a str> {
+ let mut names: Vec<&str> = drawables
+ .iter()
+ .flat_map(|(_, d)| &d.shaders)
+ .flat_map(|s| &s.samplers)
+ .filter(|(parameter, _)| wanted.contains(parameter))
+ .map(|(_, name)| name.as_str())
+ .collect();
+ names.sort_unstable();
+ names.dedup();
+ names.truncate(MAX_TEXTURES);
+ names
+}
+
+/// The textures of drawables, shared with other models: their colours, with
+/// `all` normal and specular maps too.
+pub fn shared_for(game_dir: &Path, drawables: &[(String, Drawable)], side: u32, all: bool) -> Vec> {
+ let wanted: &[u32] = if all {
+ &[DIFFUSE_TEX, DIFFUSE_TEX2, LAYER_1_TEX, BUMP_TEX, SPECULAR_TEX]
+ } else if side > 256 {
+ &[DIFFUSE_TEX, DIFFUSE_TEX2, LAYER_1_TEX]
+ } else {
+ &[DIFFUSE_TEX]
+ };
+ let names = names(drawables, wanted);
+ if names.is_empty() {
+ return Vec::new();
+ }
+ let catalog = catalog(game_dir);
+ let found = names.iter().filter_map(|n| catalog.shared(u64::from_str_radix(n, 16).ok()?, side));
+ // Not the white stand-ins for a colour the game computes.
+ let stands_in = |t: &Texture| {
+ t.width <= 8
+ && t.to_rgba().is_some_and(|rgba| rgba.as_chunks::<4>().0.iter().all(|p| p[..3].iter().all(|c| *c > 225)))
+ };
+ found.filter(|t| !stands_in(t)).collect()
+}
+
+/// The textures the shaders of these drawables name, from the pools of the
+/// game: a dictionary of them, `None` if none was found.
+pub fn for_drawables(game_dir: &Path, drawables: &[(String, Drawable)]) -> Option {
+ let names = names(drawables, &[DIFFUSE_TEX, DIFFUSE_TEX2, LAYER_1_TEX, BUMP_TEX, SPECULAR_TEX]);
+ if names.is_empty() {
+ return None;
+ }
+ let catalog = catalog(game_dir);
+ let total = names.len();
+ let mut textures = Vec::new();
+ for (i, name) in names.into_iter().enumerate() {
+ crate::progress::set("Loading textures", i as u64, total as u64);
+ if let Some(texture) = u64::from_str_radix(name, 16).ok().and_then(|key| catalog.texture(key)) {
+ textures.push(texture);
+ }
+ }
+ (!textures.is_empty()).then(|| TextureDictionary {
+ textures,
+ errors: Vec::new(),
+ layout: Layout::Enhanced,
+ version: 0,
+ root: Vec::new(),
+ stored: Vec::new(),
+ })
+}
diff --git a/crates/openrage-app/src/gta6_world.rs b/crates/openrage-app/src/gta6_world.rs
new file mode 100644
index 0000000..2f31b18
--- /dev/null
+++ b/crates/openrage-app/src/gta6_world.rs
@@ -0,0 +1,913 @@
+//! The map of GTA VI: where its map files (`.#map`) are, what they place, and
+//! the models for it.
+//!
+//! A map file covers a small piece of the world, and there are more than
+//! 160,000, so reading all of them takes a minute or two. What is needed of
+//! them is kept (`/openrage/gta6-world-.bin`) until the search
+//! index changes.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use anyhow::{Context, Result};
+use rage_core::bytes::LeRead;
+use rage_core::hash::joaat;
+use rage_formats::drawable::Drawable;
+use rage_formats::math::{self, Mat4};
+use rage_rpf::Rpf9;
+use rage_rpf::vfs::Node as Node9;
+use rayon::prelude::*;
+
+use crate::models::LoadedModel;
+use crate::world::MapScene;
+
+const MAGIC: &[u8; 8] = b"ORG6MAP2";
+
+/// Levels of detail: the models seen close, and the ones that stand for whole
+/// neighbourhoods from afar.
+const CLOSE: [u8; 2] = [0, 5];
+const FAR: u8 = 3;
+/// The levels between, up to the far one.
+const LEVELS: std::ops::RangeInclusive = 1..=FAR;
+/// How well textures are read in views of many models.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Quality {
+ /// Seen from kilometres away.
+ Far,
+ Near,
+ /// From up close: normal and specular maps too.
+ Close,
+}
+
+impl Quality {
+ fn side(self) -> u32 {
+ match self {
+ Self::Far => 256,
+ Self::Near => 512,
+ Self::Close => 1024,
+ }
+ }
+}
+
+/// Something a map file places.
+#[derive(Debug, Clone, PartialEq)]
+struct Object {
+ /// Hash of the model's name.
+ model: u32,
+ position: [f32; 3],
+ rotation: [f32; 4],
+ scale: [f32; 2],
+}
+
+impl Object {
+ fn transform(&self) -> Mat4 {
+ let [x, y, z, w] = self.rotation;
+ let [flat, high] = self.scale;
+ math::from_trs(self.position, [-x, -y, -z, w], [flat, flat, high])
+ }
+}
+
+/// An object that stands for others from afar: for those whose parent it is.
+#[derive(Debug, Clone, PartialEq)]
+struct Node {
+ /// The map file (the hash of its name) and the place in it.
+ key: (u32, u32),
+ parent: Option<(u32, u32)>,
+ level: u8,
+ /// Nearer than this, the others are shown.
+ reach: f32,
+ object: Object,
+}
+
+/// What is kept of the map files.
+#[derive(Debug, Default, PartialEq)]
+pub struct Map {
+ /// Map files with the box around what they place.
+ files: Vec<(String, [f32; 3], [f32; 3])>,
+ /// The objects that stand for others from afar.
+ nodes: Vec,
+ /// Models in dictionaries, by the hash of their name: the dictionary and
+ /// the place in it.
+ children: HashMap,
+}
+
+/// Files of the index, by the archive they are in.
+fn by_archive(list: Vec<(String, String)>, keep: impl Fn(&str) -> bool) -> BTreeMap> {
+ let mut found: BTreeMap> = BTreeMap::new();
+ for (_, vpath) in list.into_iter().filter(|(_, v)| keep(v)) {
+ if let Some((archive, file)) = vpath.rsplit_once(".rpf/") {
+ found.entry(format!("{archive}.rpf")).or_default().push(file.to_owned());
+ }
+ }
+ found
+}
+
+fn each_file(
+ game: &Path,
+ archives: &BTreeMap>,
+ work: impl Fn(&Rpf9, usize, String) + Sync,
+ done: &(dyn Fn() + Sync),
+) {
+ archives.par_iter().for_each(|(archive, files)| {
+ let Ok((Node9::Rpf9Dir(rpf, _), _)) = rage_mods::resolve(game, archive, None) else { return };
+ let Ok(entries) = rpf.entries() else { return };
+ files.par_iter().for_each(|file| {
+ if let Some(i) = rpf.find(&entries, file) {
+ work(&rpf, i, format!("{archive}/{file}"));
+ }
+ done();
+ });
+ });
+}
+
+/// The part of the text between two others.
+fn between<'a>(line: &'a str, start: &str, end: &str) -> Option<&'a str> {
+ line.strip_prefix(start)?.split(end).next()
+}
+
+fn attributes(line: &str, names: [&str; N]) -> Option<[f32; N]> {
+ let mut out = [0.0; N];
+ for (out, name) in out.iter_mut().zip(names) {
+ let at = line.find(&format!(" {name}=\""))? + name.len() + 3;
+ *out = line[at..].split('"').next()?.parse().ok()?;
+ }
+ Some(out)
+}
+
+/// The hash a name in the XML stands for.
+fn name_hash(name: &str) -> u32 {
+ let hash = name.strip_prefix("hash_").filter(|h| h.len() == 8).and_then(|h| u32::from_str_radix(h, 16).ok());
+ hash.unwrap_or_else(|| joaat(name))
+}
+
+/// What a map file holds.
+#[derive(Default)]
+struct Placements {
+ /// Hash of the file's name.
+ name: u32,
+ /// The box around what it places.
+ extent: Option<[[f32; 3]; 2]>,
+ /// In the order of the file.
+ entries: Vec,
+}
+
+/// A placed object with its place among the levels of detail.
+struct Entry {
+ level: u8,
+ parent: Option<(u32, u32)>,
+ reach: f32,
+ object: Object,
+}
+
+impl Placements {
+ fn has_close(&self) -> bool {
+ self.entries.iter().any(|e| CLOSE.contains(&e.level))
+ }
+
+ fn close(self) -> impl Iterator- {
+ self.entries.into_iter().filter(|e| CLOSE.contains(&e.level)).map(|e| e.object)
+ }
+}
+
+/// What a map file places. The XML is read by lines: there is a lot of it,
+/// and it is our own.
+fn read_map(xml: &str) -> Placements {
+ let mut map = Placements::default();
+ let (mut lo, mut hi) = (None, None);
+ let mut now = Object { model: 0, position: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 2] };
+ // The files with the objects that stand for this one's.
+ let mut parents: Vec
= Vec::new();
+ let (mut in_parents, mut in_entities, mut in_extensions) = (false, false, false);
+ let (mut reach, mut parent_index) = (0.0, -1.0);
+ let value = |line: &str| attributes(line, ["value"]).map(|[v]| v);
+ for line in xml.lines().map(str::trim) {
+ if in_extensions {
+ in_extensions = line != "";
+ } else if in_entities {
+ if line == "" || line.starts_with(" ") {
+ in_extensions = true;
+ } else if line == "" {
+ in_entities = false;
+ } else if let Some(name) = between(line, "", "<") {
+ now.model = name_hash(name);
+ } else if line.starts_with("= 0.0
+ && file >= 0.0
+ {
+ entry.parent = parents.get(file as usize).map(|file| (*file, parent_index as u32));
+ }
+ } else if line.starts_with("") || line.starts_with("");
+ } else if line == "" {
+ in_parents = true;
+ } else if line == " " {
+ in_parents = false;
+ } else if let Some(name) = between(line, "- ", "<").filter(|_| in_parents) {
+ parents.push(name_hash(name));
+ } else if let Some(name) = between(line, "
", "<").filter(|_| map.name == 0) {
+ map.name = name_hash(name);
+ } else if line.starts_with(" Vec {
+ let list = system.u64_at(32).and_then(|p| usize::try_from(p.checked_sub(0x5000_0000)?).ok());
+ let count = system.u16_at(40).unwrap_or(0);
+ let Some(list) = list else { return Vec::new() };
+ (0..usize::from(count)).map_while(|i| system.u32_at(list.checked_add(i * 4)?)).collect()
+}
+
+fn build(game: &Path, index: &rage_index::Index, progress: &(dyn Fn(usize, usize) + Sync)) -> Result {
+ let maps = by_archive(index.files_with_extensions(&[".#map"])?, |_| true);
+ let dictionaries = by_archive(index.files_with_extensions(&[".#dd"])?, |v| v.contains("/map/"));
+ let total = maps.values().chain(dictionaries.values()).map(Vec::len).sum();
+ let count = AtomicUsize::new(0);
+ let done = || {
+ let n = count.fetch_add(1, Ordering::Relaxed) + 1;
+ if n.is_multiple_of(500) {
+ progress(n, total);
+ }
+ };
+ let map = Mutex::new(Map::default());
+ let lock = || map.lock().unwrap_or_else(|e| e.into_inner());
+ each_file(
+ game,
+ &maps,
+ |rpf, i, vpath| {
+ let Ok(xml) = crate::metadata::from_rpf9(rpf, i) else { return };
+ let placements = read_map(&xml.text);
+ let mut map = lock();
+ if let Some([lo, hi]) = placements.extent.filter(|_| placements.has_close()) {
+ map.files.push((vpath, lo, hi));
+ }
+ let name = placements.name;
+ let nodes = placements.entries.into_iter().enumerate().filter(|(_, e)| LEVELS.contains(&e.level));
+ map.nodes.extend(nodes.map(|(k, e)| Node {
+ key: (name, k as u32),
+ parent: e.parent,
+ level: e.level,
+ reach: e.reach,
+ object: e.object,
+ }));
+ },
+ &done,
+ );
+ each_file(
+ game,
+ &dictionaries,
+ |rpf, i, vpath| {
+ let Ok(entries) = rpf.entries() else { return };
+ let Some((system, _)) = rpf.resource_parts(&entries[i]) else { return };
+ let Ok(start) = rpf.read_start(&entries[i], system as usize) else { return };
+ let names = dictionary(&start);
+ let mut map = lock();
+ for (k, name) in names.into_iter().enumerate() {
+ map.children.entry(name).or_insert_with(|| (vpath.clone(), k as u16));
+ }
+ },
+ &done,
+ );
+ let mut map = map.into_inner().unwrap_or_else(|e| e.into_inner());
+ map.files.sort_by(|a, b| a.0.cmp(&b.0));
+ map.nodes.sort_by_key(|n| n.key);
+ Ok(map)
+}
+
+fn cache_path(game: &Path) -> Option {
+ crate::paths::game_cache(game, "gta6-world", "bin")
+}
+
+fn encode(map: &Map, stamp: i64) -> Vec {
+ let mut out = Vec::from(MAGIC);
+ out.extend(stamp.to_le_bytes());
+ let text = |out: &mut Vec, s: &str| {
+ out.extend((s.len() as u32).to_le_bytes());
+ out.extend(s.as_bytes());
+ };
+ let floats = |out: &mut Vec, v: &[f32]| v.iter().for_each(|f| out.extend(f.to_le_bytes()));
+ out.extend((map.files.len() as u32).to_le_bytes());
+ for (path, lo, hi) in &map.files {
+ text(&mut out, path);
+ floats(&mut out, lo);
+ floats(&mut out, hi);
+ }
+ out.extend((map.nodes.len() as u32).to_le_bytes());
+ for n in &map.nodes {
+ let parent = n.parent.unwrap_or((u32::MAX, u32::MAX));
+ for v in [n.key.0, n.key.1, parent.0, parent.1, u32::from(n.level), n.object.model] {
+ out.extend(v.to_le_bytes());
+ }
+ floats(&mut out, &[n.reach]);
+ floats(&mut out, &n.object.position);
+ floats(&mut out, &n.object.rotation);
+ floats(&mut out, &n.object.scale);
+ }
+ // Dictionaries once, then their models.
+ let mut by_path: BTreeMap<&str, Vec<(u32, u16)>> = BTreeMap::new();
+ for (name, (path, k)) in &map.children {
+ by_path.entry(path).or_default().push((*name, *k));
+ }
+ out.extend((by_path.len() as u32).to_le_bytes());
+ for (path, models) in by_path {
+ text(&mut out, path);
+ out.extend((models.len() as u32).to_le_bytes());
+ for (name, k) in models {
+ out.extend(name.to_le_bytes());
+ out.extend(u32::from(k).to_le_bytes());
+ }
+ }
+ out
+}
+
+fn decode(data: &[u8], stamp: i64) -> Option {
+ let rest = data.strip_prefix(MAGIC)?.strip_prefix(&stamp.to_le_bytes())?;
+ fn floats(number: &mut impl FnMut() -> Option) -> Option<[f32; N]> {
+ let mut out = [0.0; N];
+ for f in &mut out {
+ *f = f32::from_bits(number()?);
+ }
+ Some(out)
+ }
+ let mut reader = Reader { data: rest, at: 0 };
+ let mut map = Map::default();
+ for _ in 0..reader.number()? {
+ let path = reader.text()?;
+ let (lo, hi) = (floats(&mut || reader.number())?, floats(&mut || reader.number())?);
+ map.files.push((path, lo, hi));
+ }
+ for _ in 0..reader.number()? {
+ let mut next = || reader.number();
+ let (key, parent) = ((next()?, next()?), (next()?, next()?));
+ let (level, model) = (next()? as u8, next()?);
+ let [reach] = floats(&mut next)?;
+ let object =
+ Object { model, position: floats(&mut next)?, rotation: floats(&mut next)?, scale: floats(&mut next)? };
+ map.nodes.push(Node { key, parent: (parent.0 != u32::MAX).then_some(parent), level, reach, object });
+ }
+ for _ in 0..reader.number()? {
+ let path = reader.text()?;
+ for _ in 0..reader.number()? {
+ let (name, k) = (reader.number()?, reader.number()?);
+ map.children.insert(name, (path.clone(), k as u16));
+ }
+ }
+ Some(map)
+}
+
+struct Reader<'a> {
+ data: &'a [u8],
+ at: usize,
+}
+
+impl Reader<'_> {
+ fn number(&mut self) -> Option {
+ let v = self.data.u32_at(self.at)?;
+ self.at += 4;
+ Some(v)
+ }
+
+ fn text(&mut self) -> Option {
+ let len = self.number()? as usize;
+ let bytes = self.data.get(self.at..self.at.checked_add(len)?)?;
+ self.at += len;
+ String::from_utf8(bytes.to_vec()).ok()
+ }
+}
+
+/// The game's map: kept, or read from its map files. `progress` gets the files
+/// read and their number.
+pub fn load(game: &Path, progress: &(dyn Fn(usize, usize) + Sync)) -> Result> {
+ static LOADED: Mutex)>> = Mutex::new(None);
+ let index = open_index(game)?;
+ let stamp = index.changed_at()?.unwrap_or(0);
+ let mut loaded = LOADED.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some((of, at, map)) = &*loaded
+ && of == game
+ && *at == stamp
+ {
+ return Ok(Arc::clone(map));
+ }
+ let path = cache_path(game).context("no cache directory")?;
+ let map = match std::fs::read(&path).ok().and_then(|data| decode(&data, stamp)) {
+ Some(map) => map,
+ None => {
+ let map = rage_rpf::in_own_threads(|| build(game, &index_of(game)?, progress))?;
+ let partial = path.with_extension("bin.part");
+ // The cache only saves time.
+ let _ = std::fs::write(&partial, encode(&map, stamp)).and_then(|()| std::fs::rename(&partial, &path));
+ map
+ }
+ };
+ let map = Arc::new(map);
+ *loaded = Some((game.to_path_buf(), stamp, Arc::clone(&map)));
+ Ok(map)
+}
+
+fn index_of(game: &Path) -> Result {
+ let path = crate::index_path(game).filter(|p| p.exists()).context("the search index is not built yet")?;
+ Ok(rage_index::Index::open(&path)?)
+}
+
+fn open_index(game: &Path) -> Result {
+ let index = index_of(game)?;
+ anyhow::ensure!(index.is_complete()?, "the search index is still being built");
+ Ok(index)
+}
+
+/// Where a model is.
+#[derive(Debug, Clone)]
+enum Source {
+ File(String),
+ Child(String, u16),
+}
+
+/// The files of models, by the hash of their name.
+fn model_files(game: &Path) -> Result> {
+ let list = open_index(game)?.files_with_extensions(&[".#dr", ".#ft"])?;
+ let mut found = HashMap::with_capacity(list.len());
+ for (name, vpath) in list {
+ if let Some((stem, _)) = name.rsplit_once('.') {
+ found.entry(joaat(stem)).or_insert(vpath);
+ }
+ }
+ Ok(found)
+}
+
+/// A loaded model: the hash of its name, its name, and itself.
+pub type Loaded = (u32, String, LoadedModel);
+
+/// Where the game's models are.
+struct Models<'a> {
+ game: &'a Path,
+ files: &'a HashMap,
+ map: &'a Map,
+}
+
+impl Models<'_> {
+ fn source(&self, model: u32) -> Option {
+ let file = self.files.get(&model).map(|file| Source::File(file.clone()));
+ file.or_else(|| self.map.children.get(&model).map(|(file, k)| Source::Child(file.clone(), *k)))
+ }
+
+ /// Loads models; those that cannot be read are left out.
+ fn load(&self, wanted: &[u32], quality: Quality, progress: &(dyn Fn(usize, usize) + Sync)) -> Vec {
+ // Archives are opened once: that takes longer than reading a model.
+ let mut archives: BTreeMap> = BTreeMap::new();
+ for &model in wanted {
+ let Some(source) = self.source(model) else { continue };
+ let (Source::File(vpath) | Source::Child(vpath, _)) = &source;
+ if let Some((archive, file)) = vpath.rsplit_once(".rpf/") {
+ archives.entry(format!("{archive}.rpf")).or_default().push((file.to_owned(), model, source));
+ }
+ }
+ let total = archives.values().map(Vec::len).sum();
+ let count = &AtomicUsize::new(0);
+ progress(0, total);
+ archives
+ .into_par_iter()
+ .flat_map(|(archive, files)| {
+ let opened = match rage_mods::resolve(self.game, &archive, None) {
+ Ok((Node9::Rpf9Dir(rpf, _), _)) => rpf.entries().ok().map(|entries| (rpf, entries)),
+ _ => None,
+ };
+ files.into_par_iter().filter_map(move |(file, model, source)| {
+ let loaded = opened.as_ref().and_then(|(rpf, entries)| {
+ let i = rpf.find(entries, &file)?;
+ crate::progress::quietly(|| load_model(self.game, rpf, i, &source, quality)).ok()
+ });
+ progress(count.fetch_add(1, Ordering::Relaxed) + 1, total);
+ loaded.map(|(name, loaded)| (model, name, loaded))
+ })
+ })
+ .collect()
+ }
+}
+
+/// Puts objects together: every model once, with all its places.
+fn scene(
+ game: &Path,
+ map: &Map,
+ objects: &[Object],
+ quality: Quality,
+ progress: &(dyn Fn(usize, usize) + Sync),
+) -> Result {
+ let files = model_files(game)?;
+ let models = Models { game, files: &files, map };
+ let mut places: HashMap> = HashMap::new();
+ for o in objects {
+ places.entry(o.model).or_default().push(o.transform());
+ }
+ let (wanted, unknown): (Vec, Vec) = places.keys().partition(|m| models.source(**m).is_some());
+ let mut missing: Vec<(String, usize)> =
+ unknown.into_iter().map(|m| (rage_formats::names::value(m), places[&m].len())).collect();
+ missing.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
+ let loaded = models.load(&wanted, quality, progress);
+ let models = loaded
+ .into_iter()
+ .map(|(model, name, loaded)| (name, loaded, places.remove(&model).unwrap_or_default()))
+ .collect();
+ Ok(MapScene { models, objects: objects.len(), missing })
+}
+
+fn load_model(game: &Path, rpf: &Rpf9, i: usize, source: &Source, quality: Quality) -> Result<(String, LoadedModel)> {
+ let (Source::File(vpath) | Source::Child(vpath, _)) = source;
+ let mut drawables: Vec<(String, Drawable)> = crate::gta6_models::load(rpf, i)?;
+ if let Source::Child(_, k) = source {
+ let k = usize::from(*k);
+ anyhow::ensure!(k < drawables.len(), "no such model in the dictionary");
+ drawables = vec![drawables.swap_remove(k)];
+ }
+ let name = match source {
+ Source::File(_) => vpath.rsplit('/').next().unwrap_or(vpath).to_owned(),
+ Source::Child(..) => drawables[0].0.clone(),
+ };
+ let textures = crate::gta6_textures::shared_for(game, &drawables, quality.side(), quality == Quality::Close);
+ let mut model = LoadedModel::from_drawables(drawables);
+ model.set_shared(textures);
+ Ok((name.trim_end_matches(".#dr").trim_end_matches(".#ft").to_owned(), model))
+}
+
+/// The whole map, as it looks from afar.
+pub fn overview(game: &Path, progress: &Progress) -> Result {
+ let map = load(game, &|done, total| progress("Reading the game's map files", done, total))?;
+ let far: Vec = map.nodes.iter().filter(|n| n.level == FAR).map(|n| n.object.clone()).collect();
+ anyhow::ensure!(!far.is_empty(), "the map files of this game have no distant view");
+ scene(game, &map, &far, Quality::Far, &|done, total| progress("Loading the map's models", done, total))
+}
+
+/// Gets what is being done, how much of it is done, and how much there is.
+pub type Progress<'a> = dyn Fn(&str, usize, usize) + Sync + 'a;
+
+/// How far around a map file's objects its surroundings are shown (metres).
+pub const AROUND: f32 = 120.0;
+
+/// A map file, with what the others place around it.
+pub fn place(game: &Path, vpath: &str, around: f32, progress: &Progress) -> Result {
+ let own = read_map(&crate::metadata::load(game, None, vpath)?.text);
+ let map = load(game, &|done, total| progress("Reading the game's map files", done, total))?;
+ let (extent, has_close) = (own.extent, own.has_close());
+ let mut objects: Vec =
+ if has_close { own.close().collect() } else { own.entries.into_iter().map(|e| e.object).collect() };
+ if let Some([lo, hi]) = extent.filter(|_| has_close) {
+ let middle = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0];
+ let near = |p: &[f32; 3]| (0..2).all(|k| (p[k] - middle[k]).abs() <= around);
+ let others = map.files.iter().filter(|(path, lo, hi)| {
+ path != vpath && (0..2).all(|k| lo[k] <= middle[k] + around && hi[k] >= middle[k] - around)
+ });
+ let others = by_archive(others.map(|(path, ..)| (String::new(), path.clone())).collect(), |_| true);
+ let found = Mutex::new(Vec::new());
+ each_file(
+ game,
+ &others,
+ |rpf, i, _| {
+ let Ok(xml) = crate::metadata::from_rpf9(rpf, i) else { return };
+ let near = read_map(&xml.text).close().filter(|o| near(&o.position));
+ found.lock().unwrap_or_else(|e| e.into_inner()).extend(near);
+ },
+ &|| {},
+ );
+ objects.extend(found.into_inner().unwrap_or_else(|e| e.into_inner()));
+ }
+ scene(game, &map, &objects, Quality::Near, &|done, total| progress("Loading the map's models", done, total))
+}
+
+/// How near the camera a map file has to be for its close objects (metres).
+const NEAR: f32 = 200.0;
+/// How near objects have to be that stand for others but have none above them.
+const ALONE: [f32; 4] = [0.0, 800.0, 4000.0, f32::MAX];
+
+/// The whole map in the detail that fits where the camera is.
+pub struct Lod {
+ game: PathBuf,
+ map: Arc,
+ files: HashMap,
+ /// Nodes by their key.
+ by_key: HashMap<(u32, u32), u32>,
+ /// What each node stands for, among the nodes.
+ children: Vec>,
+ roots: Vec,
+}
+
+/// The close objects of a map file, with the node they are part of.
+#[derive(Default)]
+pub struct Close {
+ objects: Vec<(Option, Object)>,
+}
+
+/// What to draw: models with their places, and what is missing for more
+/// detail, the most wanted first.
+#[derive(Default)]
+pub struct Cut {
+ pub draw: HashMap>,
+ pub wanted: Vec,
+}
+
+fn distance(a: &[f32; 3], b: &[f32; 3]) -> f32 {
+ (0..3).map(|k| (a[k] - b[k]).powi(2)).sum::().sqrt()
+}
+
+/// How far a point is from a box.
+fn distance_to_box(p: &[f32; 3], lo: &[f32; 3], hi: &[f32; 3]) -> f32 {
+ distance(p, &std::array::from_fn(|k| p[k].clamp(lo[k], hi[k].max(lo[k]))))
+}
+
+impl Lod {
+ pub fn open(game: &Path, progress: &Progress) -> Result {
+ let map = load(game, &|done, total| progress("Reading the game's map files", done, total))?;
+ Ok(Self::new(game, map, model_files(game)?))
+ }
+
+ fn new(game: &Path, map: Arc, files: HashMap) -> Self {
+ let by_key: HashMap<(u32, u32), u32> = map.nodes.iter().enumerate().map(|(i, n)| (n.key, i as u32)).collect();
+ let mut children = vec![Vec::new(); map.nodes.len()];
+ let mut roots = Vec::new();
+ for (i, node) in map.nodes.iter().enumerate() {
+ // Only of a higher level, so there are no circles.
+ let parent = node.parent.and_then(|key| by_key.get(&key).copied());
+ match parent.filter(|p| map.nodes[*p as usize].level > node.level) {
+ Some(p) => children[p as usize].push(i as u32),
+ None => roots.push(i as u32),
+ }
+ }
+ Self { game: game.to_owned(), map, files, by_key, children, roots }
+ }
+
+ /// The models of the farthest level.
+ pub fn far(&self) -> Vec {
+ let far = self.map.nodes.iter().filter(|n| n.level == FAR).map(|n| n.object.model);
+ far.collect::>().into_iter().collect()
+ }
+
+ /// Whether the game has this model.
+ pub fn has_model(&self, model: u32) -> bool {
+ self.files.contains_key(&model) || self.map.children.contains_key(&model)
+ }
+
+ /// Loads models.
+ pub fn load(&self, models: &[u32], quality: Quality, progress: &(dyn Fn(usize, usize) + Sync)) -> Vec {
+ let of = Models { game: &self.game, files: &self.files, map: &self.map };
+ of.load(models, quality, progress)
+ }
+
+ /// The map files with close objects near a place.
+ pub fn near(&self, eye: &[f32; 3], range: f32) -> HashSet {
+ let near = |(_, lo, hi): &&(String, [f32; 3], [f32; 3])| distance_to_box(eye, lo, hi) < NEAR * range;
+ (0..).zip(&self.map.files).filter(|(_, f)| near(f)).map(|(i, _)| i).collect()
+ }
+
+ /// Reads the close objects of map files.
+ pub fn read(&self, files: &[u32]) -> Vec<(u32, Close)> {
+ let number: HashMap<&str, u32> = files.iter().map(|i| (self.map.files[*i as usize].0.as_str(), *i)).collect();
+ let by_archive = by_archive(number.keys().map(|p| (String::new(), (*p).to_owned())).collect(), |_| true);
+ let found = Mutex::new(Vec::new());
+ each_file(
+ &self.game,
+ &by_archive,
+ |rpf, i, vpath| {
+ let Some(&number) = number.get(vpath.as_str()) else { return };
+ let entries = crate::metadata::from_rpf9(rpf, i).map(|x| read_map(&x.text).entries).unwrap_or_default();
+ let close = entries.into_iter().filter(|e| CLOSE.contains(&e.level));
+ let node = |e: &Entry| e.parent.and_then(|key| self.by_key.get(&key).copied());
+ let objects = close.map(|e| (node(&e), e.object)).collect();
+ found.lock().unwrap_or_else(|e| e.into_inner()).push((number, Close { objects }));
+ },
+ &|| {},
+ );
+ found.into_inner().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// What to draw from a place, `range` times as far in detail as the game
+ /// does, of the models there are, with the close
+ /// objects read so far. An object gives way to those it stands for when
+ /// all of them are there.
+ pub fn cut<'a>(
+ &self,
+ eye: &[f32; 3],
+ range: f32,
+ loaded: &dyn Fn(u32) -> bool,
+ unreadable: &dyn Fn(u32) -> bool,
+ close: impl Iterator- ,
+ ) -> Cut {
+ let mut of_node: HashMap
> = HashMap::new();
+ let mut cut = Choice {
+ lod: self,
+ eye,
+ range,
+ loaded,
+ unreadable,
+ close: HashMap::new(),
+ draw: Vec::new(),
+ wanted: HashMap::new(),
+ };
+ for (node, object) in close.flat_map(|c| &c.objects) {
+ match node {
+ Some(node) => of_node.entry(*node).or_default().push(object),
+ None if distance(eye, &object.position) < NEAR * range && cut.take(object) => cut.draw.push(object),
+ None => {}
+ }
+ }
+ cut.close = of_node;
+ for &root in &self.roots {
+ let node = &self.map.nodes[root as usize];
+ if distance(eye, &node.object.position) < ALONE[usize::from(node.level.min(FAR))] {
+ cut.visit(root);
+ }
+ }
+ let mut wanted: Vec<(u32, f32)> = cut.wanted.into_iter().collect();
+ wanted.sort_by(|a, b| a.1.total_cmp(&b.1));
+ let mut draw: HashMap> = HashMap::new();
+ for object in cut.draw {
+ draw.entry(object.model).or_default().push(object.transform());
+ }
+ Cut { draw, wanted: wanted.into_iter().map(|(m, _)| m).collect() }
+ }
+}
+
+/// A cut in the making.
+struct Choice<'a> {
+ lod: &'a Lod,
+ eye: &'a [f32; 3],
+ range: f32,
+ loaded: &'a dyn Fn(u32) -> bool,
+ unreadable: &'a dyn Fn(u32) -> bool,
+ close: HashMap>,
+ draw: Vec<&'a Object>,
+ /// Models to load, with how near they are.
+ wanted: HashMap,
+}
+
+impl<'a> Choice<'a> {
+ fn expects(&self, model: u32) -> bool {
+ self.lod.has_model(model) && !(self.unreadable)(model)
+ }
+
+ /// Whether an object's model is loaded; otherwise it is wanted. One the
+ /// game does not have does not count.
+ fn take(&mut self, object: &Object) -> bool {
+ if (self.loaded)(object.model) {
+ return true;
+ }
+ if self.expects(object.model) {
+ let far = distance(self.eye, &object.position);
+ let known = self.wanted.entry(object.model).or_insert(far);
+ *known = known.min(far);
+ }
+ false
+ }
+
+ /// Draws a node or what it stands for; gives whether something stands
+ /// where it is.
+ fn visit(&mut self, node: u32) -> bool {
+ let lod = self.lod;
+ let (n, children) = (&lod.map.nodes[node as usize], &lod.children[node as usize]);
+ if distance(self.eye, &n.object.position) < n.reach * self.range {
+ let before = self.draw.len();
+ let mut all = true;
+ let mut any = false;
+ for child in children {
+ any = true;
+ all &= self.visit(*child);
+ }
+ for object in self.close.remove(&node).unwrap_or_default() {
+ any = true;
+ if self.take(object) {
+ self.draw.push(object);
+ } else {
+ all &= !self.expects(object.model);
+ }
+ }
+ if any && all {
+ return true;
+ }
+ self.draw.truncate(before);
+ }
+ if self.take(&n.object) {
+ self.draw.push(&n.object);
+ return true;
+ }
+ !self.expects(n.object.model)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const XML: &str = r#"
+ hash_00000077
+
+ - hash_00000099
+
+
+
+
+ -
+
+
+ Prop_A
+
+
+
+
+
+
+
+ -
+
+
+
+
+ hash_0000ABCD
+
+
+
+
+
+
+
+
+ "#;
+
+ #[test]
+ fn map_files_are_read() {
+ let map = read_map(XML);
+ assert_eq!((map.name, map.extent), (0x77, Some([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])));
+ let [a, b] = &map.entries[..] else { panic!("two entries") };
+ assert_eq!((a.level, a.object.model, a.parent), (5, joaat("prop_a"), None));
+ assert_eq!(a.object.scale, [2.0, 3.0]);
+ assert_eq!(a.object.transform()[12..15], [10.0, 20.0, 30.0]);
+ assert_eq!((b.level, b.object.model, b.parent, b.reach), (2, 0xABCD, Some((0x99, 4)), 60.0));
+ }
+
+ fn node(key: (u32, u32), parent: Option<(u32, u32)>, level: u8, model: u32) -> Node {
+ let object = Object { model, position: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 2] };
+ Node { key, parent, level, reach: 100.0, object }
+ }
+
+ #[test]
+ fn the_cache_reads_back() {
+ let map = Map {
+ files: vec![("a.rpf/b.#map".into(), [1.0; 3], [2.0; 3])],
+ nodes: vec![node((1, 0), None, 3, 7), node((2, 0), Some((1, 0)), 2, 8)],
+ children: HashMap::from([(7, ("c.rpf/d.#dd".to_owned(), 3))]),
+ };
+ let data = encode(&map, 5);
+ assert_eq!(decode(&data, 5).unwrap(), map);
+ assert!(decode(&data, 6).is_none());
+ for n in 0..data.len() {
+ assert!(decode(&data[..n], 5).is_none());
+ }
+ }
+
+ #[test]
+ fn detail_follows_the_camera() {
+ let map = Map {
+ files: Vec::new(),
+ nodes: vec![
+ node((1, 0), None, 3, 10),
+ node((2, 0), Some((1, 0)), 2, 20),
+ node((2, 1), Some((1, 0)), 2, 21),
+ ],
+ children: HashMap::from([10, 20, 21, 30].map(|m| (m, (String::new(), 0)))),
+ };
+ let lod = Lod::new(Path::new(""), Arc::new(map), HashMap::new());
+ let object = Object { model: 30, position: [0.0; 3], rotation: [0.0, 0.0, 0.0, 1.0], scale: [1.0; 2] };
+ let close = Close { objects: vec![(Some(1), object)] };
+ let cut = |at: f32, loaded: &[u32]| {
+ let cut = lod.cut(&[at, 0.0, 0.0], 1.0, &|m| loaded.contains(&m), &|_| false, std::iter::once(&close));
+ let mut draw: Vec = cut.draw.into_keys().collect();
+ draw.sort_unstable();
+ (draw, cut.wanted.len())
+ };
+ // Afar, the far one; close, what it stands for once all of it is there.
+ assert_eq!(cut(500.0, &[10, 20, 21, 30]), (vec![10], 0));
+ assert_eq!(cut(50.0, &[10, 20]), (vec![10], 2));
+ assert_eq!(cut(50.0, &[10, 20, 21]), (vec![20, 21], 1));
+ assert_eq!(cut(50.0, &[10, 20, 21, 30]), (vec![21, 30], 0));
+ }
+}
diff --git a/crates/openrage-app/src/install.rs b/crates/openrage-app/src/install.rs
index 6be3459..65d9354 100644
--- a/crates/openrage-app/src/install.rs
+++ b/crates/openrage-app/src/install.rs
@@ -1,4 +1,5 @@
-//! Writing changes into the OpenIV `mods` folder.
+//! Writing changes into the OpenIV `mods` folder (RDR2: LML's `lml/replace`,
+//! see [`crate::rdr2_install`]).
//!
//! A change to a file inside a game archive is written the OpenIV way: the
//! top-level archive is copied once to `mods/` (or the copy already
@@ -221,6 +222,9 @@ pub fn apply_grouped(
) -> Result {
let mods = mods_dir_or_create(game_dir)?;
let journal = Journal::new(&mods).grouped(group);
+ if rage_mods::overlay::is_rdr2(game_dir) {
+ return crate::rdr2_install::apply(game_dir, &mods, archive, ops, description, &journal);
+ }
if archive.to_ascii_lowercase().ends_with(".img") {
return apply_img(game_dir, &mods, archive, ops, description, &journal);
}
@@ -521,6 +525,9 @@ pub fn apply_at(
/// (`mods`, GTA IV: `update`) at the same path, so the game loads it instead
/// of its own; recorded for undo. Returns the written file.
pub fn put_loose(game_dir: &Path, vpath: &str, data: &[u8], description: &str) -> Result {
+ if rage_mods::overlay::is_rdr2(game_dir) {
+ bail!("{vpath}: for RDR2 only files inside the game's archives can be replaced (through lml/replace)");
+ }
let mods = mods_dir_or_create(game_dir)?;
let folder = rage_mods::overlay::folder_name(game_dir);
let rel = vpath.trim_start_matches('/');
@@ -556,6 +563,9 @@ pub fn remove_loose(game_dir: &Path, vpath: &str, description: &str) -> Result<(
/// Creates a new, empty top-level archive in the mods folder (e.g. a new DLC pack).
pub fn create_archive(game_dir: &Path, archive: &str, description: &str, group: Option<&str>) -> Result {
+ if rage_mods::overlay::is_rdr2(game_dir) {
+ bail!("{archive}: new top-level archives are not loaded for RDR2");
+ }
let mods = mods_dir_or_create(game_dir)?;
let safe = vfs::safe_relative_path(archive).with_context(|| format!("{archive}: not a valid path"))?;
let dest = mods.join(safe);
diff --git a/crates/openrage-app/src/lib.rs b/crates/openrage-app/src/lib.rs
index 6af0cd4..4eac124 100644
--- a/crates/openrage-app/src/lib.rs
+++ b/crates/openrage-app/src/lib.rs
@@ -14,6 +14,9 @@ pub mod extract;
pub mod gta4;
pub mod gta4_cutscene;
pub mod gta4_effects;
+pub mod gta6_models;
+pub mod gta6_textures;
+pub mod gta6_world;
pub mod install;
pub mod journal;
pub mod licenses;
@@ -24,17 +27,22 @@ pub mod models;
pub mod natives;
pub mod obj;
pub mod oiv;
+pub mod openformats;
+pub mod palette;
pub mod paths;
pub mod plugins;
pub mod progress;
pub mod rdr2;
+pub mod rdr2_install;
pub mod render;
pub mod repack;
+pub mod rpf9;
pub mod setup;
pub mod suggest;
pub mod texttable;
pub mod textures;
pub mod tint;
+pub mod vehicle_mods;
pub mod world;
pub mod xmltree;
diff --git a/crates/openrage-app/src/media.rs b/crates/openrage-app/src/media.rs
index 9a74364..632805f 100644
--- a/crates/openrage-app/src/media.rs
+++ b/crates/openrage-app/src/media.rs
@@ -1,4 +1,4 @@
-//! Facts about Scaleform movies (`.gfx`) and Bink videos (`.bik`) for display.
+//! Facts about Scaleform movies (`.gfx`) and Bink videos (`.bik`, `.bk2`) for display.
use anyhow::Result;
@@ -15,18 +15,26 @@ fn short_list(names: &[String]) -> String {
}
/// Facts about a media file, as (label, value) rows.
-pub fn rows(name: &str, data: &[u8]) -> Result> {
+pub fn rows(data: &[u8]) -> Result> {
use rage_formats::media;
- let lower = name.to_ascii_lowercase();
- Ok(if lower.ends_with(".bik") {
- let b = media::bink(data)?;
- vec![
- ("Format".into(), format!("Bink video ({})", b.signature)),
- ("Resolution".into(), format!("{} × {}", b.width, b.height)),
- ("Frames".into(), format!("{} at {:.2} fps", b.frames, b.fps)),
- ("Length".into(), format!("{:.1} s", b.duration())),
- ("Audio tracks".into(), b.audio_tracks.to_string()),
- ]
+ Ok(if rage_formats::bink::is_bink(data) {
+ let v = rage_formats::bink::read(data)?;
+ let mut rows = vec![
+ ("Format".into(), format!("Bink {} video, revision {}", v.version, v.revision as char)),
+ (
+ "Resolution".into(),
+ format!("{} × {}{}", v.width, v.height, if v.has_alpha() { ", with alpha" } else { "" }),
+ ),
+ ("Frames".into(), format!("{} at {:.2} fps", v.frames(), v.frames_per_second())),
+ ("Length".into(), format!("{:.1} s", v.duration())),
+ ];
+ let tracks: Vec = v
+ .tracks
+ .iter()
+ .map(|t| format!("{} Hz, {}", t.sample_rate, if t.channels == 2 { "stereo" } else { "mono" }))
+ .collect();
+ rows.push(("Sound".into(), if tracks.is_empty() { "none".into() } else { tracks.join("; ") }));
+ rows
} else {
let g = media::gfx(data)?;
vec![
diff --git a/crates/openrage-app/src/metadata.rs b/crates/openrage-app/src/metadata.rs
index ef10faa..4ae297a 100644
--- a/crates/openrage-app/src/metadata.rs
+++ b/crates/openrage-app/src/metadata.rs
@@ -12,7 +12,10 @@ use rage_resource::Resource;
use rage_rpf::vfs::Node;
/// Extensions of files that hold metadata.
-pub const EXTENSIONS: &[&str] = &["ymap", "ytyp", "ymt", "ymf", "cut", "pso"];
+pub const EXTENSIONS: &[&str] = &[
+ "ymap", "ytyp", "ymt", "ymf", "cut", "pso", "psin", "rbf0", "#mt", "#map", "#typ", "#ldb", "#ldbmt", "#as", "#cov",
+ "#kit", "#fc", "#lfc",
+];
pub fn is_metadata(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
@@ -72,6 +75,11 @@ fn from_bytes_for(data: &[u8], rdr2: bool) -> Result {
}
return from_resource(&res);
}
+ if rage_formats::psin::is_psin(data) {
+ let psin = rage_formats::psin::parse(data)?;
+ let (text, errors) = psin.to_xml();
+ return Ok(Xml { text, encoding: Encoding::Pso, root: Some(psin.root_type()), errors });
+ }
if rage_formats::pso::is_pso(data) {
let pso = if rdr2 { rage_formats::pso::parse_rdr2(data)? } else { rage_formats::pso::parse(data)? };
let (text, errors) = pso.to_xml();
@@ -109,6 +117,16 @@ pub fn from_rpf8(rpf: &rage_rpf::Rpf8, i: usize) -> Result {
from_bytes_rdr2(&rpf.read(entry)?)
}
+/// Converts a metadata file in a GTA VI archive (resource or PSO) to XML.
+pub fn from_rpf9(rpf: &rage_rpf::Rpf9, i: usize) -> Result {
+ match crate::rpf9::resource(rpf, i) {
+ Ok((system, graphics)) if rage_formats::meta::is_gta6(&system) => {
+ from_resource(&Resource { version: rage_formats::meta::VERSION_RDR2, system, graphics })
+ }
+ _ => from_bytes(&rpf.read_at(i)?),
+ }
+}
+
/// Reads a metadata file (mods included) and converts it to XML.
pub fn load(game_dir: &Path, keys: Option>, vpath: &str) -> Result {
let (node, _) = rage_mods::resolve(game_dir, vpath, keys)?;
@@ -116,6 +134,7 @@ pub fn load(game_dir: &Path, keys: Option>, vpath: &str) -> Result
Node::ArchiveFile(rpf, id) => rpf.read(id)?,
Node::PlainFile(p) => std::fs::read(p)?,
Node::Rpf8File(rpf, i) => return from_rpf8(&rpf, i),
+ Node::Rpf9File(rpf, i) => return from_rpf9(&rpf, i),
_ => bail!("{vpath} is not a file"),
};
from_bytes(&data)
diff --git a/crates/openrage-app/src/models.rs b/crates/openrage-app/src/models.rs
index 6b0b23a..2cdcc7d 100644
--- a/crates/openrage-app/src/models.rs
+++ b/crates/openrage-app/src/models.rs
@@ -38,6 +38,8 @@ pub struct LoadedModel {
pub parts: Vec,
/// Texture dictionaries found next to the model (`.ytd`, `vehshare.ytd`).
pub external: Vec<(String, TextureDictionary)>,
+ /// Textures shared with other models (GTA VI).
+ shared: Vec>,
/// Materials: shaders with the same name across all drawables.
pub materials: Vec,
/// The skeleton skinned meshes are bound to (for peds: from the `.yft`
@@ -111,6 +113,7 @@ impl LoadedModel {
parts,
external: Vec::new(),
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton: None,
expressions: Vec::new(),
@@ -123,7 +126,24 @@ impl LoadedModel {
/// Finds a texture by name: embedded in the drawable first, then next to the model.
pub fn texture<'a>(&'a self, drawable: &'a Drawable, name: &str) -> Option<&'a Texture> {
let find = |d: &'a TextureDictionary| d.textures.iter().find(|t| t.name.eq_ignore_ascii_case(name));
- drawable.textures.as_ref().and_then(find).or_else(|| self.external.iter().find_map(|(_, d)| find(d)))
+ let own = drawable.textures.as_ref().and_then(find).or_else(|| self.external.iter().find_map(|(_, d)| find(d)));
+ own.or_else(|| self.shared_texture(name).map(|t| &**t))
+ }
+
+ /// The texture of this name that is shared with other models.
+ pub(crate) fn shared_texture(&self, name: &str) -> Option<&Arc> {
+ self.shared.iter().find(|t| t.name.eq_ignore_ascii_case(name))
+ }
+
+ /// Gives the model textures it shares with others.
+ pub fn set_shared(&mut self, textures: Vec>) {
+ self.shared = textures;
+ self.collect_materials();
+ }
+
+ /// Lets go of the shared textures: what shows the model has them.
+ pub fn forget_shared(&mut self) {
+ self.shared = Vec::new();
}
/// Dresses a GTA IV ped: for each (component, drawable, texture) — a
@@ -272,6 +292,21 @@ impl LoadedModel {
/// Ped component names (`head_000_r`, `uppr_001_u`, …) by hash: drawable
/// dictionaries of peds only store the hashes.
+/// The names of a `.ydd`'s drawables as the viewer shows them (and OBJ
+/// export names their parts): ped components by name (`uppr_000_u`), others
+/// `#`, or `#` without a hash.
+pub fn dictionary_names(stem: &str, hashes: &[u32]) -> Vec {
+ hashes
+ .iter()
+ .enumerate()
+ .map(|(i, &hash)| match ped_component_names().get(&hash) {
+ Some(n) => n.clone(),
+ None if hash != 0 => format!("{stem}#{hash:08x}"),
+ None => format!("{stem}#{i}"),
+ })
+ .collect()
+}
+
fn ped_component_names() -> &'static HashMap {
static NAMES: OnceLock> = OnceLock::new();
NAMES.get_or_init(|| {
@@ -371,7 +406,7 @@ fn streamed_ped(rpf: &rage_rpf::Rpf7, folder: rage_rpf::EntryId) -> Result (Vec<(String, Drawable)>, Vec) {
- let drawable::Fragment { drawable: body, children } = fragment;
+ let drawable::Fragment { drawable: body, children, cloths } = fragment;
let skeleton = body.skeleton.clone().unwrap_or_default();
let world = skeleton.world_transforms();
let mut drawables = vec![(name.to_owned(), body)];
@@ -383,6 +418,20 @@ fn fragment_parts(fragment: drawable::Fragment, name: &str) -> (Vec<(String, Dra
visible: true,
bone: None,
}];
+ // Cloth (RDR2's flags and straps) in its rest pose: the game moves it.
+ for (k, cloth) in cloths.into_iter().enumerate() {
+ let label = if k == 0 { "cloth".to_owned() } else { format!("cloth_{k}") };
+ let index = drawables.len();
+ parts.push(Part {
+ name: label.clone(),
+ group: "Cloth".into(),
+ drawable: index,
+ transform: math::IDENTITY,
+ visible: true,
+ bone: None,
+ });
+ drawables.push((label, cloth));
+ }
let mut wheels: Vec<(String, usize)> = Vec::new();
for child in children {
let bone = skeleton.find_tag(child.bone_tag);
@@ -391,11 +440,13 @@ fn fragment_parts(fragment: drawable::Fragment, name: &str) -> (Vec<(String, Dra
let index = drawables.len();
drawables.push((bone_name.clone(), child.drawable));
let transform = bone.and_then(|b| world.get(b)).copied().unwrap_or(math::IDENTITY);
- if bone_name.starts_with("wheel_") {
+ // RDR2's blurred wheels for high speeds (`wheel_lf_fast`) stay hidden.
+ let variant = is_wheel_variant(&bone_name);
+ if bone_name.starts_with("wheel_") && !variant {
wheels.push((bone_name.clone(), index));
}
let group = if bone_name.starts_with("wheel_") { "Wheels" } else { "Parts" };
- parts.push(Part { name: bone_name, group: group.into(), drawable: index, transform, visible: true, bone });
+ parts.push(Part { name: bone_name, group: group.into(), drawable: index, transform, visible: !variant, bone });
}
// Copy wheels to the wheel bones that have no drawable of their own.
if !wheels.is_empty() {
@@ -403,7 +454,7 @@ fn fragment_parts(fragment: drawable::Fragment, name: &str) -> (Vec<(String, Dra
let is_rear = |n: &str| n.ends_with('r') || n.contains("_lm") || n.contains("_rm");
for (b, bone) in skeleton.bones.iter().enumerate() {
let n = bone.name.to_ascii_lowercase();
- let is_wheel_bone = n.starts_with("wheel_") && !n.contains("mesh");
+ let is_wheel_bone = n.starts_with("wheel_") && !n.contains("mesh") && !is_wheel_variant(&n);
if !is_wheel_bone || wheels.iter().any(|(w, _)| w.eq_ignore_ascii_case(&n)) {
continue;
}
@@ -432,6 +483,64 @@ fn fragment_parts(fragment: drawable::Fragment, name: &str) -> (Vec<(String, Dra
(drawables, parts)
}
+/// A vehicle's mod parts ([`crate::vehicle_mods`]), hidden at first, each on
+/// the bone the game puts it on, grouped by kind (`Mods: bonnet`).
+fn add_mod_parts(
+ game_dir: &Path,
+ keys: Option>,
+ vehicle: &str,
+ drawables: &mut Vec<(String, Drawable)>,
+ parts: &mut Vec,
+) {
+ let Some(skeleton) = drawables.first().and_then(|(_, d)| d.skeleton.clone()) else { return };
+ // Vehicles only: their skeleton has a chassis.
+ if skeleton.find_name("chassis").is_none() {
+ return;
+ }
+ let world = skeleton.world_transforms();
+ let mods = crate::vehicle_mods::mod_parts(game_dir, keys.clone(), vehicle);
+ let total = mods.len() as u64;
+ for (k, m) in mods.into_iter().enumerate() {
+ crate::progress::set("Loading the mod parts", k as u64, total);
+ let Ok((Node::ArchiveFile(rpf, id), _)) = rage_mods::resolve(game_dir, &m.vpath, keys.clone()) else {
+ continue;
+ };
+ let Some(fragment) = rpf.read_resource(id).ok().and_then(|r| drawable::parse_fragment(&r).ok()) else {
+ continue;
+ };
+ if fragment.drawable.meshes.is_empty() {
+ continue;
+ }
+ // By name, or by its hash where `carcols` keeps one.
+ let bone = m.bone.as_deref().and_then(|b| {
+ let hash = rage_formats::names::parse(&b.to_ascii_lowercase());
+ skeleton.find_name(b).or_else(|| {
+ skeleton.bones.iter().position(|x| rage_core::hash::joaat(&x.name.to_ascii_lowercase()) == hash)
+ })
+ });
+ let kind = m.kind.as_deref().map(crate::vehicle_mods::kind_label).unwrap_or_else(|| "other".into());
+ parts.push(Part {
+ name: m.name.clone(),
+ group: format!("Mods: {kind}"),
+ drawable: drawables.len(),
+ transform: bone.and_then(|b| world.get(b)).copied().unwrap_or(math::IDENTITY),
+ visible: false,
+ bone,
+ });
+ let mut d = fragment.drawable;
+ // Its own one-bone skeleton is not the vehicle's.
+ d.skeleton = None;
+ drawables.push((m.name, d));
+ }
+}
+
+/// RDR2 wheel bones besides the wheel itself: the blurred one shown at
+/// speed (`wheel_lf_fast`) and the one for upgrades (`wheel_lf_mod`).
+fn is_wheel_variant(bone: &str) -> bool {
+ let n = bone.to_ascii_lowercase();
+ n.starts_with("wheel_") && (n.ends_with("_fast") || n.ends_with("_mod"))
+}
+
pub fn is_model(name: &str) -> bool {
let n = name.to_ascii_lowercase();
n.ends_with(".ydr")
@@ -444,6 +553,12 @@ pub fn is_model(name: &str) -> bool {
|| n.ends_with(".wft")
|| n.ends_with(".wbn")
|| n.ends_with(".wbd")
+ // GTA VI: drawables, fragments and drawable dictionaries.
+ || n.ends_with(".#dr")
+ || n.ends_with(".#ft")
+ || n.ends_with(".#dd")
+ || n.ends_with(".#bn")
+ || n.ends_with(".#nv")
|| rage_formats::paths::is_path_file(&n)
}
@@ -502,7 +617,8 @@ fn register_gta4_materials(archive: &rage_rpf::Gta4Archive, bounds: &[(String, D
}
/// Names of the collision materials, read once from the game's `materials.dat`.
-fn collision_material_names(game_dir: &Path, keys: Option>) -> &'static [String] {
+/// The names of the game's collision materials (`materials.dat`), by type.
+pub fn collision_material_names(game_dir: &Path, keys: Option>) -> &'static [String] {
static NAMES: std::sync::OnceLock> = std::sync::OnceLock::new();
NAMES.get_or_init(|| {
for path in ["update/update.rpf/common/data/materials/materials.dat", "common.rpf/data/materials/materials.dat"]
@@ -585,13 +701,45 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
if let Node::Gta4File(archive, id) = node {
return load_gta4(&archive, id);
}
+ if let Node::Rpf9File(rpf, i) = node {
+ if vpath.to_ascii_lowercase().ends_with(".#bn") {
+ let (system, _) = crate::rpf9::resource(&rpf, i)?;
+ let (collision, stats) = rage_formats::bn6::parse(&system)?;
+ for material in stats.materials {
+ let label = format!("Material {material:04x}");
+ let color = material_color(&label, material as u8);
+ let id = rage_formats::ybn::MATERIAL_BASE + u32::from(material);
+ rage_formats::shaders::register(id, label, color);
+ }
+ return Ok(LoadedModel::from_drawables(vec![("collision".to_owned(), collision)]));
+ }
+ if vpath.to_ascii_lowercase().ends_with(".#nv") {
+ let (mesh, _) = rage_formats::paths::parse_nv6(crate::rpf9::resource(&rpf, i)?.0)?;
+ return Ok(LoadedModel::from_drawables(vec![("nav mesh".to_owned(), mesh)]));
+ }
+ let mut drawables = crate::gta6_models::load(&rpf, i)?;
+ let textures = crate::gta6_textures::for_drawables(game_dir, &drawables);
+ let name = vpath.rsplit('/').next().unwrap_or(vpath);
+ // A dictionary's drawables have skeletons of their own.
+ let worn_on = crate::gta6_models::bind(game_dir, name, &mut drawables);
+ let skeleton = worn_on.or_else(|| match drawables.as_slice() {
+ [(_, d)] => d.skeleton.clone(),
+ _ => None,
+ });
+ let mut model = LoadedModel::from_drawables(drawables);
+ model.skeleton = skeleton;
+ if let Some(textures) = textures {
+ model.add_textures("texture pools".to_owned(), textures);
+ }
+ return Ok(model);
+ }
let Node::ArchiveFile(rpf, id) = node else { bail!("{vpath} is not a file inside an archive") };
let name = rpf.entry(id).name.clone();
let res = rpf.read_resource(id)?;
let lower = name.to_ascii_lowercase();
let stem = name.split('.').next().unwrap_or(&name).to_owned();
let mut external = Vec::new();
- let (drawables, parts) = if rage_formats::paths::is_path_file(&lower) {
+ let (mut drawables, mut parts) = if rage_formats::paths::is_path_file(&lower) {
let ext = lower.rsplit('.').next().unwrap_or_default();
let (path, _) = rage_formats::paths::parse(&res, ext)?;
let part = Part {
@@ -655,18 +803,10 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
}
(drawables, parts)
} else if lower.ends_with(".ydd") {
- let drawables: Vec<(String, Drawable)> = drawable::parse_ydd(&res)?
- .into_iter()
- .enumerate()
- .map(|(i, (hash, d))| {
- let name = match ped_component_names().get(&hash) {
- Some(n) => n.clone(),
- None if hash != 0 => format!("{stem}#{hash:08x}"),
- None => format!("{stem}#{i}"),
- };
- (name, d)
- })
- .collect();
+ let parsed = drawable::parse_ydd(&res)?;
+ let hashes: Vec = parsed.iter().map(|(h, _)| *h).collect();
+ let drawables: Vec<(String, Drawable)> =
+ dictionary_names(&stem, &hashes).into_iter().zip(parsed).map(|(name, (_, d))| (name, d)).collect();
let names: Vec = drawables.iter().map(|(n, _)| n.clone()).collect();
// Peds are assembled in place; other dictionaries are laid out in a grid.
let layout =
@@ -702,6 +842,7 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
parts,
external,
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton,
expressions: Vec::new(),
@@ -725,6 +866,10 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
bail!("{name} is not a model (.ydr, .yft, .ydd, .ypt, .ybn, .ynd, .yvr, .ywr)");
};
+ if lower.ends_with(".yft") {
+ add_mod_parts(game_dir, keys.clone(), &stem, &mut drawables, &mut parts);
+ }
+
// Textures usually live next to the model: adder.yft → adder.ytd (+ vehshare.ytd for vehicles).
let dir = rpf.entry(id).parent.unwrap_or(rage_rpf::Rpf7::ROOT);
let mut candidates = vec![format!("{stem}.ytd"), format!("{stem}+hi.ytd")];
@@ -775,7 +920,6 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
let tid = rpf.find_child(dir, &format!("{stem}.yft"))?;
drawable::parse_fragment(&rpf.read_resource(tid).ok()?).ok()?.drawable.skeleton
});
- let mut drawables = drawables;
if let Some(sk) = &skeleton {
fit_to_skeleton(&mut drawables, sk);
}
@@ -784,6 +928,7 @@ fn load_model(game_dir: &Path, keys: Option>, vpath: &str) -> Resu
parts,
external,
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton,
expressions: Vec::new(),
@@ -1260,6 +1405,7 @@ fn load_gta4(archive: &Arc, id: rage_rpf::Gta4EntryId) ->
parts,
external,
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton,
expressions: Vec::new(),
@@ -1323,6 +1469,7 @@ fn gta4_player(archive: &rage_rpf::Gta4Archive, skeleton: drawable::Skeleton) ->
parts,
external,
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton: Some(skeleton),
expressions: Vec::new(),
@@ -1363,6 +1510,7 @@ pub fn load_gta4_members(game: &Path, vpath: &str, wanted: &[(String, u32)]) ->
parts: vec![part],
external,
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton: d.skeleton.clone(),
expressions: Vec::new(),
@@ -1400,7 +1548,7 @@ fn load_rdr2(rpf: &Arc, i: usize) -> Result {
})
.collect()
} else if lower.ends_with(".yft") {
- vec![(stem.clone(), drawable::parse_fragment_rdr2(&res)?.drawable)]
+ Vec::new()
} else {
bail!("{name}: only .ydr, .ydd and .yft models of Red Dead Redemption 2 can be shown so far");
};
@@ -1411,23 +1559,30 @@ fn load_rdr2(rpf: &Arc, i: usize) -> Result {
if let Some(sk) = &base {
fit_to_skeleton(&mut drawables, sk);
}
- let layout = if drawables.len() > 1 && base.is_none() {
- grid_layout(&drawables)
+ let parts = if lower.ends_with(".yft") {
+ // Fragments: the body and its children (wheels) on their bones.
+ let (d, p) = fragment_parts(drawable::parse_fragment_rdr2(&res)?, &stem);
+ drawables = d;
+ p
} else {
- vec![math::IDENTITY; drawables.len()]
+ let layout = if drawables.len() > 1 && base.is_none() {
+ grid_layout(&drawables)
+ } else {
+ vec![math::IDENTITY; drawables.len()]
+ };
+ drawables
+ .iter()
+ .enumerate()
+ .map(|(k, (n, _))| Part {
+ name: n.clone(),
+ group: String::new(),
+ drawable: k,
+ transform: layout[k],
+ visible: true,
+ bone: None,
+ })
+ .collect()
};
- let parts = drawables
- .iter()
- .enumerate()
- .map(|(k, (n, _))| Part {
- name: n.clone(),
- group: String::new(),
- drawable: k,
- transform: layout[k],
- visible: true,
- bone: None,
- })
- .collect();
// Texture dictionaries in the same folder: `.ytd` first, then those
// whose name shares the model's prefix, then the rest; at most eight.
let dir = full.rsplit_once('/').map_or("", |(d, _)| d).to_owned();
@@ -1469,6 +1624,8 @@ fn load_rdr2(rpf: &Arc, i: usize) -> Result {
// The rest from shared dictionaries elsewhere, through the texture index.
if let Some(game) = crate::rdr2::game_folder(rpf.path()) {
rdr2_shared_textures(&game, &drawables, &mut external, 32);
+ // Palette shaders: colours from the palettes (vehicles: their first variation).
+ crate::palette::apply(&crate::palette::carvariations(&game), &stem, &mut drawables, &mut external);
}
let skeleton = base.or_else(|| drawables.iter().find_map(|(_, d)| d.skeleton.clone()));
let mut model = LoadedModel {
@@ -1476,6 +1633,7 @@ fn load_rdr2(rpf: &Arc, i: usize) -> Result {
parts,
external,
materials: Vec::new(),
+ shared: Vec::new(),
shader_material: Vec::new(),
skeleton,
expressions: Vec::new(),
@@ -1595,13 +1753,8 @@ fn load_rdr2_ped_inner(game: &Path, ped: &str, outfit: usize) -> Result Result Option {
+pub(crate) fn rdr2_base_skeleton(rpf: &rage_rpf::Rpf8, stem: &str) -> Option {
rdr2_base_skeleton_in(&crate::rdr2::game_folder(rpf.path())?, stem)
}
+/// The file of an RDR2 ped's base skeleton, as the ped list names it (`meta_base_male.yft`).
+pub(crate) fn rdr2_ped_base(game: &Path, ped: &str) -> Option {
+ let peds = crate::metaped::peds(game).ok()?;
+ peds.iter().find(|p| p.name.eq_ignore_ascii_case(ped)).map(crate::metaped::base_fragment)
+}
+
+/// The skeleton an RDR2 ped is put together on: as the ped list names it,
+/// else guessed from the ped's name.
+pub(crate) fn rdr2_ped_skeleton(game: &Path, ped: &str) -> Option {
+ rdr2_ped_base(game, ped)
+ .and_then(|frag| rdr2_skeleton_named(game, &frag))
+ .or_else(|| rdr2_base_skeleton_in(game, ped))
+}
+
+/// The archive with RDR2's base skeletons (`metaped_fragments.rpf`).
+pub(crate) fn rdr2_base_skeletons(game: &Path) -> Option> {
+ match rage_mods::resolve(game, RDR2_BASE_SKELETONS, None).ok()?.0 {
+ Node::Rpf8Dir(frags, _) => Some(frags),
+ _ => None,
+ }
+}
+
/// A base skeleton by its file name (`meta_base_male.yft`).
-fn rdr2_skeleton_named(game: &Path, file: &str) -> Option {
+pub(crate) fn rdr2_skeleton_named(game: &Path, file: &str) -> Option {
let (Node::Rpf8Dir(frags, _), _) = rage_mods::resolve(game, RDR2_BASE_SKELETONS, None).ok()? else {
return None;
};
@@ -1994,6 +2170,41 @@ mod tests {
assert!(mesh.bone_tags.is_empty());
}
+ #[test]
+ fn rdr2_wheels_on_their_bones() {
+ let bone = |name: &str, tag: u16, x: f32| drawable::Bone {
+ name: name.into(),
+ tag,
+ parent: if tag == 0 { -1 } else { 0 },
+ rotation: [0.0, 0.0, 0.0, 1.0],
+ translation: [x, 0.0, 0.0],
+ scale: [1.0; 3],
+ };
+ let names = ["chassis", "wheel_lf", "wheel_lf_fast", "wheel_rf", "wheel_rf_fast", "wheel_rf_mod"];
+ let bones = names.iter().enumerate().map(|(i, n)| {
+ let x = match (i, n.contains("_r")) {
+ (0, _) => 0.0,
+ (_, true) => 1.0,
+ _ => -1.0,
+ };
+ bone(n, i as u16, x)
+ });
+ let body = Drawable { skeleton: Some(drawable::Skeleton { bones: bones.collect() }), ..Default::default() };
+ let wheel = |tag| drawable::FragmentChild { bone_tag: tag, drawable: Drawable::default() };
+ let cloth = Drawable { meshes: vec![drawable::Mesh::default()], ..Default::default() };
+ let fragment = drawable::Fragment { drawable: body, children: vec![wheel(1), wheel(2)], cloths: vec![cloth] };
+ let (drawables, parts) = fragment_parts(fragment, "cart");
+ assert_eq!(drawables.len(), 4);
+ let shown: Vec<(&str, bool)> = parts.iter().map(|p| (p.name.as_str(), p.visible)).collect();
+ // The cloth in place; the blurred wheel hidden; only the plain right wheel gets a copy.
+ let expected =
+ [("cart", true), ("cloth", true), ("wheel_lf", true), ("wheel_lf_fast", false), ("wheel_rf", true)];
+ assert_eq!(shown, expected);
+ assert_eq!((parts[1].group.as_str(), parts[1].transform), ("Cloth", math::IDENTITY));
+ assert_eq!(parts[4].drawable, 2);
+ assert_eq!(parts[4].transform[12], 1.0);
+ }
+
#[test]
fn cloth_follows_the_nearest_bones() {
// A thigh going down from the pelvis, and the spine going up.
diff --git a/crates/openrage-app/src/obj.rs b/crates/openrage-app/src/obj.rs
index dc1360d..1b9053b 100644
--- a/crates/openrage-app/src/obj.rs
+++ b/crates/openrage-app/src/obj.rs
@@ -11,7 +11,8 @@ use std::sync::Arc;
use anyhow::{Context, Result, bail};
use rage_crypto::GtaVKeys;
use rage_formats::texture::Texture;
-use rage_formats::ydr_write::{MAX_VERTICES, NewMaterial, NewMesh, ShaderInfo};
+use rage_formats::ydr_write::{Blend, MAX_VERTICES, NewMaterial, NewMesh, Place, ShaderInfo};
+use rage_resource::Resource;
use rage_rpf::vfs::Node;
/// Triangles of one material.
@@ -240,23 +241,6 @@ pub fn decode_png(data: &[u8]) -> Result<(u32, u32, Vec)> {
Ok((info.width, info.height, rgba))
}
-/// Puts OBJ meshes of one or more detail levels on materials: every OBJ
-/// material (by name, across levels) becomes one [`NewMaterial`] on a
-/// template shader (in order, the last taking the rest, or all on `shader`)
-/// with its texture, if `textures` has one.
-pub struct Fitter<'a> {
- shaders: &'a [u16],
- shader: Option,
- textures: &'a HashMap,
- /// (OBJ material name, material)
- pub materials: Vec<(String, NewMaterial)>,
- bones: Option,
- infos: Vec,
- /// Materials whose texture was not used: their shader takes none, so
- /// it keeps its own.
- pub textures_kept: Vec,
-}
-
/// The template shader a material is named after: OpenRAGE's OBJ export
/// names materials `_` and their images after the
/// texture, so exported models go back on the shaders they came from.
@@ -283,8 +267,34 @@ pub fn fit_texture(infos: &[ShaderInfo], shader: u16, texture: Option)
}
}
+/// What a part's name says, without what tools add: after a dot
+/// (`door_dside_f.001`), a level suffix (`_lod1`); with and without a number
+/// at the end (`door_dside_f_3`, from OpenRAGE's OBJ export).
+fn name_candidates(part: &str) -> (String, Option) {
+ let lower = part.trim().to_ascii_lowercase();
+ let base = lower.split('.').next().unwrap_or("");
+ let base = (1..=3).find_map(|k| base.strip_suffix(&format!("_lod{k}"))).unwrap_or(base);
+ let numbered = base
+ .rsplit_once('_')
+ .filter(|(_, n)| !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit()))
+ .map(|(b, _)| b.to_owned());
+ (base.to_owned(), numbered)
+}
+
+/// The index of the name in `names` a part is named after (names that keep
+/// their number, such as `extra_1`, first).
+fn find_name>(names: &[S], part: &str) -> Option {
+ let (base, numbered) = name_candidates(part);
+ // OBJ export writes names with `_` for other characters (`ped#1a2b` → `ped_1a2b`).
+ let safe = |n: &str| -> String {
+ n.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' { c.to_ascii_lowercase() } else { '_' }).collect()
+ };
+ let find = |n: &str| names.iter().position(|b| safe(b.as_ref()) == safe(n));
+ find(&base).or_else(|| numbered.and_then(|n| find(&n)))
+}
+
/// Puts parts of a model on the bones of a skeleton by name (vehicles:
-/// `door_dside_f`, `bonnet`, `wheel_lf` …); other parts go on the body.
+/// `door_dside_f`, `bonnet` …); other parts go on the body.
#[derive(Debug, Clone)]
pub struct Bones {
names: Vec,
@@ -308,6 +318,13 @@ impl Bones {
Self { names, body, own_models: Vec::new(), matched: Vec::new(), unmatched: Vec::new(), left_out: Vec::new() }
}
+ /// Whether the skeleton is a vehicle's (it has `chassis` or `bodyshell`):
+ /// parts go on bones by name. Other skinned models (peds) take their
+ /// weights from the original mesh ([`Weights`]).
+ pub fn is_vehicle(names: &[String]) -> bool {
+ names.iter().any(|n| n.eq_ignore_ascii_case("chassis") || n.eq_ignore_ascii_case("bodyshell"))
+ }
+
/// Bones that have a model of their own (a fragment's wheels): parts
/// named like them are left out, as the game draws those models there.
pub fn with_own_models(mut self, bones: Vec) -> Self {
@@ -317,17 +334,7 @@ impl Bones {
/// The skeleton index of the bone a part is named after.
fn find(&self, part: &str) -> Option {
- let lower = part.trim().to_ascii_lowercase();
- let base = lower.split('.').next().unwrap_or("");
- let base = (1..=3).find_map(|k| base.strip_suffix(&format!("_lod{k}"))).unwrap_or(base);
- let find = |n: &str| self.names.iter().position(|b| b.eq_ignore_ascii_case(n));
- // OBJ exports number their objects (`door_dside_f_3`); bones such as
- // `extra_1` keep their number when they exist.
- let numbered = base
- .rsplit_once('_')
- .filter(|(_, n)| !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit()))
- .map(|(b, _)| b);
- find(base).or_else(|| numbered.and_then(find))
+ find_name(&self.names, part)
}
/// Whether a part is left out: named after a bone with a model of its own.
@@ -366,96 +373,522 @@ impl Bones {
}
}
-impl<'a> Fitter<'a> {
- pub fn new(shaders: &'a [u16], shader: Option, textures: &'a HashMap) -> Result {
- if shaders.is_empty() {
- bail!("the template has no shader meshes can use");
+/// Bone weights for new vertices of a model blended between bones (peds,
+/// clothing), taken from the nearest vertex of the original meshes: an OBJ
+/// file has no place for weights, so a new mesh moves as the original did
+/// where it lies.
+#[derive(Debug, Clone)]
+pub struct Weights {
+ points: Vec<[f32; 3]>,
+ blends: Vec,
+ min: [f32; 3],
+ cell: f32,
+ cells: HashMap<[i32; 3], Vec>,
+}
+
+impl Weights {
+ /// From the original meshes' vertices that carry bones; `None` if none do.
+ pub fn from_meshes(meshes: &[rage_formats::drawable::Mesh]) -> Option {
+ let mut points = Vec::new();
+ let mut blends = Vec::new();
+ for m in meshes {
+ if m.bone_indices.len() != m.positions.len() || m.bone_weights.len() != m.positions.len() {
+ continue;
+ }
+ for i in 0..m.positions.len() {
+ if m.positions[i].iter().all(|v| v.is_finite()) {
+ points.push(m.positions[i]);
+ blends.push(Blend { bones: m.bone_indices[i], weights: m.bone_weights[i] });
+ }
+ }
}
- if let Some(s) = shader
- && !shaders.contains(&s)
- {
- bail!("shader {s} cannot be used; the template has {shaders:?}");
+ if points.is_empty() {
+ return None;
+ }
+ let (mut min, mut max) = ([f32::MAX; 3], [f32::MIN; 3]);
+ for p in &points {
+ for k in 0..3 {
+ min[k] = min[k].min(p[k]);
+ max[k] = max[k].max(p[k]);
+ }
+ }
+ // About four points per cell.
+ let volume = (0..3).map(|k| (max[k] - min[k]).max(1e-3)).product::();
+ let cell = (volume / points.len() as f32 * 4.0).cbrt().max(1e-3);
+ let mut cells: HashMap<[i32; 3], Vec> = HashMap::new();
+ let mut w = Self { points, blends, min, cell, cells: HashMap::new() };
+ for (i, p) in w.points.iter().enumerate() {
+ cells.entry(w.cell_of(*p)).or_default().push(i as u32);
}
- Ok(Self {
+ w.cells = cells;
+ Some(w)
+ }
+
+ fn cell_of(&self, p: [f32; 3]) -> [i32; 3] {
+ std::array::from_fn(|k| ((p[k] - self.min[k]) / self.cell).floor().clamp(-1e6, 1e6) as i32)
+ }
+
+ /// The bones and weights of the original vertex nearest to `p`.
+ pub fn nearest(&self, p: [f32; 3]) -> Blend {
+ let c = self.cell_of(p);
+ let (mut best, mut best_d) = (0usize, f32::MAX);
+ let d2 = |q: [f32; 3]| (0..3).map(|k| (q[k] - p[k]) * (q[k] - p[k])).sum::();
+ // Rings of cells around p until no closer point can be in the next one.
+ for r in 0..=8i32 {
+ for x in -r..=r {
+ for y in -r..=r {
+ for z in -r..=r {
+ if x.abs().max(y.abs()).max(z.abs()) != r {
+ continue;
+ }
+ if let Some(list) = self.cells.get(&[c[0] + x, c[1] + y, c[2] + z]) {
+ for &i in list {
+ let d = d2(self.points[i as usize]);
+ if d < best_d {
+ (best, best_d) = (i as usize, d);
+ }
+ }
+ }
+ }
+ }
+ }
+ let reach = r as f32 * self.cell;
+ if best_d < f32::MAX && best_d <= reach * reach {
+ break;
+ }
+ }
+ // Far from the original mesh: search everything.
+ let reach = 8.0 * self.cell;
+ if best_d > reach * reach {
+ for (i, q) in self.points.iter().enumerate() {
+ let d = d2(*q);
+ if d < best_d {
+ (best, best_d) = (i, d);
+ }
+ }
+ }
+ self.blends[best]
+ }
+}
+
+/// A place of the template that parts of a model go to: the main drawable,
+/// a fragment child's model (a wheel), a drawable of a `.ydd`.
+#[derive(Debug, Clone)]
+pub struct Target {
+ pub place: Place,
+ /// Parts named like one of these go here (a wheel bone, a dictionary
+ /// drawable's name); see [`Fitter::with_targets`] for the others.
+ pub names: Vec,
+ /// From model space to the place's own (a wheel: its bone's inverse).
+ to_local: Option,
+ shaders: Vec,
+ infos: Vec,
+ bones: Option,
+ weights: Option,
+ /// (OBJ material name, material)
+ pub materials: Vec<(String, NewMaterial)>,
+ /// Materials whose texture was not used: their shader takes none, so
+ /// it keeps its own.
+ pub textures_kept: Vec,
+ /// Parts that went here.
+ pub parts: Vec,
+}
+
+impl Target {
+ /// `shaders`: the template shaders meshes there can use.
+ pub fn new(place: Place, names: Vec, shaders: Vec) -> Self {
+ Self {
+ place,
+ names,
+ to_local: None,
shaders,
- shader,
- textures,
- materials: Vec::new(),
- bones: None,
infos: Vec::new(),
+ bones: None,
+ weights: None,
+ materials: Vec::new(),
textures_kept: Vec::new(),
- })
+ parts: Vec::new(),
+ }
}
- /// What the template's shaders look like ([`rage_formats::ydr_write::shader_infos`]):
- /// materials named after a shader's texture go on it, and textures go
- /// only to shaders that can take one.
+ /// What the shaders look like ([`rage_formats::ydr_write::shader_infos_at`]).
pub fn with_shader_info(mut self, infos: Vec) -> Self {
self.infos = infos;
self
}
- /// Puts the parts on these bones (templates with skinned meshes).
+ /// Meshes there are in the space of a bone placed at `transform` (model
+ /// space, column-major): the OBJ's positions are moved into it.
+ pub fn in_bone_space(mut self, transform: &rage_formats::math::Mat4) -> Self {
+ self.to_local = Some(rage_formats::math::inverse_affine(transform));
+ self
+ }
+
pub fn with_bones(mut self, bones: Bones) -> Self {
self.bones = Some(bones);
self
}
- /// The bones parts went on, after [`Self::level`].
+ pub fn with_weights(mut self, weights: Weights) -> Self {
+ self.weights = Some(weights);
+ self
+ }
+
pub fn bones(&self) -> Option<&Bones> {
self.bones.as_ref()
}
- /// The meshes of one level, their `shader` the index of their material.
- pub fn level(&mut self, meshes: Vec) -> Vec {
- let mut out = Vec::new();
+ /// Whether the new vertices take their weights from the original mesh.
+ pub fn has_weights(&self) -> bool {
+ self.weights.is_some()
+ }
+}
+
+/// Puts OBJ meshes of one or more detail levels on the places of a template
+/// ([`Target`]) and on materials: every OBJ material (by name, across levels)
+/// of a place becomes one [`NewMaterial`] on a template shader (in order, the
+/// last taking the rest, or all on `shader`) with its texture, if `textures`
+/// has one.
+pub struct Fitter<'a> {
+ shader: Option,
+ textures: &'a HashMap,
+ targets: Vec,
+ /// The target parts named after none go to.
+ default: Option,
+ /// Parts named after no place, when there is no default place.
+ pub unplaced: Vec,
+ /// Materials named `#n` whose shader `n` cannot be used where they are.
+ pub unusable: Vec,
+}
+
+impl<'a> Fitter<'a> {
+ /// For the main drawable only, whose meshes can use `shaders`.
+ pub fn new(shaders: &[u16], shader: Option, textures: &'a HashMap) -> Result {
+ Self::with_targets(vec![Target::new(Place::Main, Vec::new(), shaders.to_vec())], Some(0), shader, textures)
+ }
+
+ /// For several places; parts named after none go to `targets[default]`
+ /// (none: they are left out, listed in [`Self::unplaced`]).
+ pub fn with_targets(
+ targets: Vec,
+ default: Option,
+ shader: Option,
+ textures: &'a HashMap,
+ ) -> Result {
+ if let Some(t) = targets.iter().find(|t| t.shaders.is_empty()) {
+ bail!("{:?}: the template has no shader meshes can use there", t.place);
+ }
+ if targets.is_empty() {
+ bail!("the template has no place for meshes");
+ }
+ if let Some(s) = shader
+ && !targets.iter().any(|t| t.shaders.contains(&s))
+ {
+ bail!("shader {s} cannot be used; the template has {:?}", targets[0].shaders);
+ }
+ Ok(Self { shader, textures, targets, default, unplaced: Vec::new(), unusable: Vec::new() })
+ }
+
+ /// What the template's shaders look like ([`rage_formats::ydr_write::shader_infos`]):
+ /// materials named after a shader's texture go on it, and textures go
+ /// only to shaders that can take one. For the first place.
+ pub fn with_shader_info(mut self, infos: Vec) -> Self {
+ self.targets[0].infos = infos;
+ self
+ }
+
+ /// Puts the parts of the first place on these bones (templates with skinned meshes).
+ pub fn with_bones(mut self, bones: Bones) -> Self {
+ self.targets[0].bones = Some(bones);
+ self
+ }
+
+ /// The bones parts of the first place went on, after [`Self::level`].
+ pub fn bones(&self) -> Option<&Bones> {
+ self.targets[0].bones.as_ref()
+ }
+
+ pub fn targets(&self) -> &[Target] {
+ &self.targets
+ }
+
+ pub fn into_targets(self) -> Vec {
+ self.targets
+ }
+
+ /// The materials of the first place.
+ pub fn materials(&self) -> &[(String, NewMaterial)] {
+ &self.targets[0].materials
+ }
+
+ /// The target a part goes to.
+ fn target_of(&mut self, part: &str) -> Option {
+ let named = self.targets.iter().position(|t| find_name(&t.names, part).is_some());
+ let k = named.or(self.default);
+ match k {
+ Some(k) if !self.targets[k].parts.iter().any(|p| p == part) => self.targets[k].parts.push(part.to_owned()),
+ None if !self.unplaced.iter().any(|p| p == part) => self.unplaced.push(part.to_owned()),
+ _ => {}
+ }
+ k
+ }
+
+ /// The meshes of one level per place (in the order of the targets),
+ /// their `shader` the index of their material at that place.
+ pub fn level(&mut self, meshes: Vec) -> Vec> {
+ let mut out: Vec> = vec![Vec::new(); self.targets.len()];
for m in meshes {
- let m = match &mut self.bones {
- Some(b) => {
- let out: Vec = m.part_names.iter().map(|p| b.leaves_out(p)).collect();
- if out.contains(&true) { without_triangles(m, |part| out[part as usize]) } else { m }
+ let of: Vec> = m.part_names.iter().map(|p| self.target_of(p)).collect();
+ for (k, slot) in out.iter_mut().enumerate() {
+ let piece = if of.iter().all(|t| *t == Some(k)) {
+ m.clone()
+ } else if of.contains(&Some(k)) {
+ without_triangles(m.clone(), |part| of[part as usize] != Some(k))
+ } else {
+ continue;
+ };
+ slot.extend(self.fit(k, piece));
+ }
+ }
+ out
+ }
+
+ /// One mesh at a place: moved into its space, on a material, its
+ /// vertices on bones.
+ fn fit(&mut self, k: usize, mut m: ObjMesh) -> Vec {
+ let shader_opt = self.shader;
+ let textures = self.textures;
+ let unusable = &mut self.unusable;
+ let t = &mut self.targets[k];
+ // Only the parts that still have vertices here (others went to other places).
+ let present = |m: &ObjMesh| -> Vec {
+ let mut p = vec![false; m.part_names.len()];
+ m.parts.iter().for_each(|&k| p[k as usize] = true);
+ p
+ };
+ if let Some(b) = &mut t.bones {
+ let here = present(&m);
+ let out: Vec = m.part_names.iter().zip(&here).map(|(p, &h)| h && b.leaves_out(p)).collect();
+ if out.contains(&true) {
+ m = without_triangles(m, |part| out[part as usize]);
+ }
+ }
+ if m.indices.is_empty() {
+ return Vec::new();
+ }
+ if let Some(to) = &t.to_local {
+ m.positions.iter_mut().for_each(|p| *p = rage_formats::math::transform_point(to, *p));
+ m.normals.iter_mut().for_each(|n| *n = rage_formats::math::transform_dir(to, *n));
+ }
+ let i = match t.materials.iter().position(|(name, _)| *name == m.material) {
+ Some(i) => i,
+ None => {
+ let i = t.materials.len();
+ let texture = textures.get(&m.material).cloned();
+ let last = *t.shaders.last().expect("checked");
+ let explicit = m.material.strip_prefix('#').and_then(|n| n.parse::().ok());
+ if explicit.is_some_and(|s| !t.shaders.contains(&s)) && !unusable.contains(&m.material) {
+ unusable.push(m.material.clone());
}
- None => m,
- };
- if m.indices.is_empty() {
- continue;
+ let shader = explicit
+ .filter(|s| t.shaders.contains(s))
+ .or(shader_opt.filter(|s| t.shaders.contains(s)))
+ .or_else(|| shader_named(&t.infos, &m.material, texture.as_ref().map(|t| t.name.as_str())))
+ .filter(|s| t.shaders.contains(s))
+ .unwrap_or_else(|| *t.shaders.get(i).unwrap_or(&last));
+ let (texture, kept) = fit_texture(&t.infos, shader, texture);
+ if kept {
+ t.textures_kept.push(m.material.clone());
+ }
+ t.materials.push((m.material.clone(), NewMaterial { shader, texture }));
+ i
}
- let k = match self.materials.iter().position(|(name, _)| *name == m.material) {
- Some(k) => k,
- None => {
- let i = self.materials.len();
- let texture = self.textures.get(&m.material).cloned();
- let shader = self.shader.unwrap_or_else(|| {
- shader_named(&self.infos, &m.material, texture.as_ref().map(|t| t.name.as_str()))
- .unwrap_or_else(|| *self.shaders.get(i).unwrap_or(self.shaders.last().expect("checked")))
- });
- let (texture, kept) = fit_texture(&self.infos, shader, texture);
- if kept {
- self.textures_kept.push(m.material.clone());
- }
- self.materials.push((m.material.clone(), NewMaterial { shader, texture }));
- i
+ };
+ let bones = match &mut t.bones {
+ Some(b) => {
+ let here = present(&m);
+ let of: Vec =
+ m.part_names.iter().zip(&here).map(|(p, &h)| if h { b.bone_of(p) } else { 0 }).collect();
+ m.parts.iter().map(|&p| of[p as usize]).collect()
+ }
+ None => Vec::new(),
+ };
+ let blend = match &t.weights {
+ Some(w) => m.positions.iter().map(|p| w.nearest(*p)).collect(),
+ None => Vec::new(),
+ };
+ split(NewMesh {
+ shader: i as u16,
+ positions: m.positions,
+ normals: m.normals,
+ uvs: m.uvs,
+ colors: Vec::new(),
+ indices: m.indices,
+ bones,
+ blend,
+ })
+ }
+}
+
+/// The places of a template that an OBJ's parts can go to, as
+/// [`Fitter::with_targets`] takes them: the main drawable (with its bones for
+/// vehicles, weights from the original for other skinned models) and the
+/// models of fragment children (wheels: parts named after their bone), or the
+/// drawables of a `.ydd` (`names`: theirs, by index; parts named after one go
+/// to it, the rest to `drawable` if given). Returns the targets and the default.
+pub fn targets(
+ template: &Resource,
+ dictionary: Option<(&[String], Option)>,
+) -> Result<(Vec, Option)> {
+ use rage_formats::ydr_write as w;
+ let place_target = |place: Place, names: Vec| -> Result {
+ let mut t = Target::new(place, names, w::usable_shaders_at(template, place)?)
+ .with_shader_info(w::shader_infos_at(template, place)?);
+ if w::is_skinned_at(template, place)? {
+ let original = w::read_at(template, place)?;
+ let bones: Option> =
+ original.skeleton.as_ref().map(|s| s.bones.iter().map(|b| b.name.clone()).collect());
+ match bones {
+ Some(names) if Bones::is_vehicle(&names) => {
+ t = t.with_bones(Bones::new(names).with_own_models(w::bones_with_own_models(template)))
}
- };
- let bones = match &mut self.bones {
- Some(b) => {
- let of: Vec = m.part_names.iter().map(|p| b.bone_of(p)).collect();
- m.parts.iter().map(|&p| of[p as usize]).collect()
+ _ => {
+ if let Some(weights) = Weights::from_meshes(&original.meshes) {
+ t = t.with_weights(weights);
+ }
}
- None => Vec::new(),
- };
- out.extend(split(NewMesh {
- shader: k as u16,
- positions: m.positions,
- normals: m.normals,
- uvs: m.uvs,
- colors: Vec::new(),
- indices: m.indices,
- bones,
- }));
+ }
}
- out
+ Ok(t)
+ };
+ if let Some((names, drawable)) = dictionary {
+ let targets = (0..names.len())
+ .map(|i| place_target(Place::Entry(i), vec![names[i].clone()]))
+ .collect::>>()?;
+ return Ok((targets, drawable));
+ }
+ let mut targets = vec![place_target(Place::Main, Vec::new())?];
+ for (i, child) in w::child_models(template).into_iter().enumerate() {
+ // Children this writer cannot fill (no usable geometry) keep their models.
+ let Ok(t) = place_target(Place::Child(i), vec![child.bone.clone()]) else { continue };
+ if t.shaders.is_empty() {
+ continue;
+ }
+ targets.push(t.in_bone_space(&child.transform));
+ }
+ Ok((targets, Some(0)))
+}
+
+/// What [`import`] needs besides the model.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct ImportOptions<'a> {
+ /// Every material on this shader (where it can be used).
+ pub shader: Option,
+ /// `.ydd`: the drawable parts named after none go to (its name or index).
+ pub drawable: Option<&'a str>,
+}
+
+/// A written model and where its parts went.
+pub struct Imported {
+ pub file: Vec,
+ pub targets: Vec,
+ /// Parts of a `.ydd` model named after none of its drawables (left out).
+ pub unplaced: Vec,
+ /// Detail levels of the closest place written.
+ pub levels: usize,
+}
+
+/// The places of the model at `vpath` (a `.ydr`, `.yft` or `.ydd` of GTA V
+/// Enhanced) parts can go to ([`targets`]).
+pub fn targets_of(template: &Resource, vpath: &str, drawable: Option<&str>) -> Result<(Vec, Option)> {
+ let lower = vpath.to_ascii_lowercase();
+ if !lower.ends_with(".ydd") {
+ if drawable.is_some() {
+ bail!("--drawable is for drawable dictionaries (.ydd)");
+ }
+ return targets(template, None);
}
+ let stem = lower.rsplit('/').next().unwrap_or(&lower).trim_end_matches(".ydd");
+ let hashes = rage_formats::ydr_write::entry_hashes(template)?;
+ let names = crate::models::dictionary_names(stem, &hashes);
+ let default = match drawable {
+ None => None,
+ Some(d) => Some(
+ find_name(&names, d)
+ .or_else(|| d.parse::().ok().filter(|&i| i < names.len()))
+ .with_context(|| format!("{vpath} has no drawable {d:?}; it has {}", names.join(", ")))?,
+ ),
+ };
+ targets(template, Some((&names, default)))
+}
+
+/// Writes OBJ meshes (one list per detail level) into the model `template`
+/// at `vpath`: every part to its place ([`targets_of`]), checked to read back.
+/// `donor` is asked for a texture structure when the model has none.
+pub fn import(
+ template: &Resource,
+ vpath: &str,
+ levels: Vec>,
+ textures: &HashMap,
+ options: ImportOptions,
+ donor: impl FnOnce() -> Option,
+) -> Result {
+ use rage_formats::ydr_write as w;
+ let (targets, default) = targets_of(template, vpath, options.drawable)?;
+ let mut fitter = Fitter::with_targets(targets, default, options.shader, textures)?;
+ let fitted: Vec>> = levels.into_iter().map(|l| fitter.level(l)).collect();
+ if !fitter.unusable.is_empty() {
+ bail!("materials {}: no such shader can be used there", fitter.unusable.join(", "));
+ }
+ let parts = parts_of(&fitter, &fitted)?;
+ let needs_donor = parts.iter().any(|(_, _, m)| m.iter().any(|m| m.texture.is_some()));
+ let donor = (needs_donor && !w::can_donate_textures(template)).then(donor).flatten();
+ let lods: Vec> = parts.iter().map(|(_, l, _)| l.iter().map(Vec::as_slice).collect()).collect();
+ let write_parts: Vec = parts
+ .iter()
+ .zip(&lods)
+ .map(|((place, _, mats), l)| w::Part { place: *place, lods: l, materials: Some(mats) })
+ .collect();
+ let file = w::replace_parts(template, &write_parts, donor.as_ref())?;
+ // What the game gets must read back.
+ let back = Resource::from_rsc7(&file)?;
+ if vpath.to_ascii_lowercase().ends_with(".ydd") {
+ rage_formats::drawable::parse_ydd(&back).context("the built model does not read back")?;
+ } else {
+ w::read_back(&file).context("the built model does not read back")?;
+ }
+ for (place, _, _) in &parts {
+ w::read_at(&back, *place).with_context(|| format!("{place:?} does not read back"))?;
+ }
+ let levels = parts.first().map_or(0, |(_, l, _)| l.len());
+ let unplaced = std::mem::take(&mut fitter.unplaced);
+ Ok(Imported { file, targets: fitter.into_targets(), unplaced, levels })
+}
+
+/// The levels per target, as [`rage_formats::ydr_write::Part`]s need them:
+/// for every target with meshes in the closest level, its levels up to the
+/// first empty one, and its materials.
+#[allow(clippy::type_complexity)]
+pub fn parts_of(
+ fitter: &Fitter,
+ levels: &[Vec>],
+) -> Result>, Vec)>> {
+ let mut out = Vec::new();
+ for (k, t) in fitter.targets().iter().enumerate() {
+ let lods: Vec> =
+ levels.iter().map(|l| l.get(k).cloned().unwrap_or_default()).take_while(|l| !l.is_empty()).collect();
+ if lods.is_empty() {
+ if levels.iter().any(|l| l.get(k).is_some_and(|m| !m.is_empty())) {
+ bail!("{:?}: meshes only for further detail levels, none for the closest", t.place);
+ }
+ continue;
+ }
+ out.push((t.place, lods, t.materials.iter().map(|(_, m)| m.clone()).collect()));
+ }
+ if out.is_empty() {
+ bail!("no meshes for the model: every part was left out");
+ }
+ Ok(out)
}
/// An Enhanced drawable with embedded textures (or a texture dictionary),
@@ -467,7 +900,7 @@ pub fn find_texture_donor(
keys: Option>,
) -> Option