Compare commits

..
29 Commits
Author SHA1 Message Date
meehl 3af5e3dccb chore: Release rusty-path-of-building version 0.2.7
Release / create-release (push) Successful in 5s
2025-11-02 17:52:39 +01:00
meehl 76a1b4691d Add missing icon 2025-11-02 17:06:21 +01:00
meehl e877b599c1 Fix UI scaling factor not being applied at startup on X11
On wayland an event it dispatched right after window creation.
 This is not the case on X11 so we need to set it manually.
2025-11-02 15:42:53 +01:00
meehl cc38e31dbb Update known issues section in README 2025-11-02 10:08:44 +01:00
meehl 2739c45181 Use better name for context 2025-11-02 09:53:37 +01:00
meehl 18b05338bf Tweak wording of README 2025-11-02 00:40:33 +01:00
meehl 73ebb1655a Add Flatpak to README
Close #7
2025-11-01 23:40:59 +01:00
meehl 87ff0968d8 Fix missing window title during installation step 2025-10-31 16:39:09 +01:00
meehl 54b454f8b9 chore: Release rusty-path-of-building version 0.2.6
Release / create-release (push) Successful in 7s
2025-10-31 01:06:18 +01:00
meehl 6d0975fe15 Update CHANGELOG 2025-10-31 01:05:49 +01:00
meehl 64960b8c3c Add stubs for DPI scale overrides 2025-10-31 00:17:50 +01:00
meehl cf518a2c40 Add regular variant of Fontin font 2025-10-31 00:07:49 +01:00
meehl bf588528ca chore: Release rusty-path-of-building version 0.2.5
Release / create-release (push) Successful in 5s
2025-10-30 20:18:42 +01:00
meehl db98ba627b Update CHANGELOG for new release 2025-10-30 20:17:50 +01:00
meehl 479b7196cf Add support for "faux italics" 2025-10-30 20:15:02 +01:00
David Truby a338ff02f1 Fix bug accidentally requiring extra features for surface format
On my system, surface_formats() has `Rgba16Unorm` as the first format in
the surface_caps.formats vector that isn't SRGB. However if this format
is used it requires a couple of extra WGPU features that weren't
requested for the device.

This specific format isn't actually required and so the features aren't
required, so instead we can just skip over any formats that require
features when skipping srgb ones. This results in an appropriate format
being selected and gets rid of a potential wgpu crash.
2025-10-30 19:32:31 +01:00
meehl f9b29d4645 chore: Release rusty-path-of-building version 0.2.4
Release / create-release (push) Successful in 4s
2025-10-30 15:59:10 +01:00
meehl 33f1984862 Update CHANGELOG for new release 2025-10-30 15:57:57 +01:00
K900 c2318f9929 api/paths: fix Lua interop, use data directory for storage 2025-10-30 15:34:10 +01:00
meehl 1648aa5736 Add support for new 'fontin' fonts 2025-10-30 13:20:58 +01:00
meehl 43b20ecd0d Refactor font loading 2025-10-30 13:10:42 +01:00
meehl fff5aa8596 Add support for loading webp images 2025-10-30 10:00:26 +01:00
meehl 032a450d7e Fix scrolling of gem selection dropdown 2025-10-30 08:46:36 +01:00
meehl 0881080b3f chore: Release rusty-path-of-building version 0.2.3
Release / create-release (push) Successful in 7s
2025-10-29 16:26:44 +01:00
meehl 07784a848c Prepare CHANGELOG for patch release 2025-10-29 16:26:12 +01:00
Mykola bdf128addc Implement exponential backoff for github HTTP GET requests (#4) 2025-10-29 16:08:21 +01:00
meehl 7e7b4a75c8 chore: Release rusty-path-of-building version 0.2.2
Release / create-release (push) Canceled after 0s
2025-10-29 15:28:50 +01:00
meehl f5954446d1 Fix version file 2025-10-29 12:12:52 +01:00
meehl e6bdba1137 Add missing runtime dependency to README and adjust wording 2025-10-28 23:36:40 +01:00
25 changed files with 569 additions and 199 deletions

No files matched your search

+62 -1
View File
@@ -2,6 +2,61 @@
## [Unreleased] - ReleaseDate ## [Unreleased] - ReleaseDate
## [0.2.7] - 2025-11-02
### Added
- Add missing window icon. Note for package maintainers: On Wayland, the name of the `.desktop` file entries needs to match RustyPoB's `app_id`. `app_id` is set to either `rusty-path-of-building-1` or `rusty-path-of-building-2`, depending on the game argument.
### Fixed
- Fix missing window title during installation step
- Fix UI scaling factor not being applied at startup on X11
## [0.2.6] - 2025-10-31
### Added
- Add regular variant of Fontin font
- Add stubs for DPI scale overrides
## [0.2.5] - 2025-10-30
### Added
- Add support for "faux italics"
### Fixed
- Fix crash that occurs due to surface format selection not filtering out formats that require unrequested GPU features
## [0.2.4] - 2025-10-30
### Added
- Add support for loading webp images
- Add support for new 'fontin' fonts
### Changed
- Use `~/.local/share/RustyPathOfBuilding{1,2}/userdata` as default location for settings and build files. Builds files created prior to this change need to be manually copied from the old location in `~/Documents/`. Sorry about the inconvenience.
### Fixed
- Fix scrolling of gem selection dropdown
## [0.2.3] - 2025-10-29
### Added
- Add exponential backoff for github requests
## [0.2.2] - 2025-10-29
### Fixed
- Fix version file
## [0.2.1] - 2025-10-28 ## [0.2.1] - 2025-10-28
### Added ### Added
@@ -56,8 +111,14 @@
- First release - First release
<!-- next-url --> <!-- next-url -->
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.1...HEAD [Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.7...HEAD
[0.2.7]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.6...v0.2.7
[0.2.6]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.5...v0.2.6
[0.2.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.4...v0.2.5
[0.2.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.3...v0.2.4
[0.2.3]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.2...v0.2.3
[0.2.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.1...v0.2.2
[0.2.1]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.0...v0.2.1 [0.2.1]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.2...v0.2.0 [0.2.0]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.2...v0.2.0
[0.1.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.1...v0.1.2 [0.1.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.1...v0.1.2
Generated
+12 -1
View File
@@ -1120,6 +1120,7 @@ checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"byteorder-lite", "byteorder-lite",
"image-webp",
"moxcms", "moxcms",
"num-traits", "num-traits",
"png", "png",
@@ -1129,6 +1130,16 @@ dependencies = [
"zune-jpeg", "zune-jpeg",
] ]
[[package]]
name = "image-webp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
"byteorder-lite",
"quick-error",
]
[[package]] [[package]]
name = "imgref" name = "imgref"
version = "1.12.0" version = "1.12.0"
@@ -2519,7 +2530,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]] [[package]]
name = "rusty-path-of-building" name = "rusty-path-of-building"
version = "0.2.1" version = "0.2.7"
dependencies = [ dependencies = [
"ahash", "ahash",
"anyhow", "anyhow",
+2 -2
View File
@@ -4,7 +4,7 @@ authors = ["meehl"]
description = "Cross-platform runtime for Path of Building" description = "Cross-platform runtime for Path of Building"
repository = "https://github.com/meehl/rusty-path-of-building" repository = "https://github.com/meehl/rusty-path-of-building"
license = "MIT" license = "MIT"
version = "0.2.1" version = "0.2.7"
edition = "2024" edition = "2024"
publish = false publish = false
@@ -21,7 +21,7 @@ euclid = { version = "0.22.11", features = ["bytemuck"] }
fast_image_resize = { version = "5.3.0", features = ["image"] } fast_image_resize = { version = "5.3.0", features = ["image"] }
flate2 = "1.1.2" flate2 = "1.1.2"
glob = "0.3.3" glob = "0.3.3"
image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png"] } image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png", "webp"] }
log = "0.4" log = "0.4"
mlua = { version = "0.11.2", features = ["luajit", "anyhow"] } mlua = { version = "0.11.2", features = ["luajit", "anyhow"] }
nohash-hasher = "0.2.0" nohash-hasher = "0.2.0"
+10 -5
View File
@@ -1,8 +1,8 @@
# Rusty Path of Building # Rusty Path of Building
Rusty Path of Building is a cross-platform runtime for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). Like the [official runtime](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), it serves as a host environment for PoB by implementing the API used by the application's Lua logic, as well as rendering, window management, and input handling. Rusty Path of Building is a cross-platform runtime environment for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). Like [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), PoB's official runtime environment, it implements the API functions required by PoB's Lua code, handles window management and input, and renders the UI.
This project was primarily created to allow Path of Building to run natively on Linux. It is written in Rust (in case you couldn't already tell from the unimaginative name) and is designed to work across all platforms, though only Linux has been tested so far. The primary goal of this project is to provide native Linux support for Path of Building. It is written in Rust with cross-platform compatibility in mind and also runs on Windows, though testing there has been minimal.
## Usage ## Usage
@@ -10,16 +10,18 @@ This project was primarily created to allow Path of Building to run natively on
rusty-path-of-building [poe1|poe2] rusty-path-of-building [poe1|poe2]
``` ```
NOTE: The first run takes a bit longer because Path of Building's assets need to be downloaded.
## Installation ## Installation
### Arch (AUR) ### Arch (AUR)
[![Stable version badge](https://img.shields.io/aur/version/rusty-path-of-building?style=flat&label=rusty-path-of-building)](https://aur.archlinux.org/packages/rusty-path-of-building) [![Stable version badge](https://img.shields.io/aur/version/rusty-path-of-building)](https://aur.archlinux.org/packages/rusty-path-of-building)
Please check [the Arch Wiki](https://wiki.archlinux.org/title/Arch_User_Repository) on how to install packages from the AUR. Please check [the Arch Wiki](https://wiki.archlinux.org/title/Arch_User_Repository) on how to install packages from the AUR.
### Flathub
[![Stable version badge](https://img.shields.io/flathub/v/community.pathofbuilding.PathOfBuilding)](https://flathub.org/en/apps/community.pathofbuilding.PathOfBuilding)
### Building from source ### Building from source
`LuaJIT` needs to be installed on your system for the `mlua` crate to compile. `LuaJIT` needs to be installed on your system for the `mlua` crate to compile.
@@ -34,6 +36,7 @@ Path of Building's Lua code requires the following C libraries:
- [Lua-cURLv3](https://github.com/Lua-cURL/Lua-cURLv3) - [Lua-cURLv3](https://github.com/Lua-cURL/Lua-cURLv3)
- [luautf8](https://github.com/starwing/luautf8) - [luautf8](https://github.com/starwing/luautf8)
- [luasocket](https://github.com/lunarmodules/luasocket)
- `lzip` - The source is included in this repo under `lua/libs/lzip` and requires [zlib](https://www.zlib.net/) to compile. Build it with `make LUA_IMPL=luajit`. - `lzip` - The source is included in this repo under `lua/libs/lzip` and requires [zlib](https://www.zlib.net/) to compile. Build it with `make LUA_IMPL=luajit`.
Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.html#pdf-package.cpath) to see how it locates libraries. Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.html#pdf-package.cpath) to see how it locates libraries.
@@ -41,3 +44,5 @@ Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.ht
## Known Issues ## Known Issues
- The clipboard doesn't work with Wayland compositors that don't support the data-control extension(s). It is recommended to fall back to `Xwayland` in these cases. This can be done by unsetting `WAYLAND_DISPLAY`. More info here: https://github.com/1Password/arboard?tab=readme-ov-file#backend-support - The clipboard doesn't work with Wayland compositors that don't support the data-control extension(s). It is recommended to fall back to `Xwayland` in these cases. This can be done by unsetting `WAYLAND_DISPLAY`. More info here: https://github.com/1Password/arboard?tab=readme-ov-file#backend-support
- Overriding UI scaling through the options is currently not implemented.
- If automatic updates fail, navigate to `~/.local/share/RustyPathOfBuilding{1,2}/` and delete both the `rpob.version` file and the `Update` directory. This will force a complete re-download of PoB's latest assets and Lua code on the next startup. (Note: Third-party backends, like this project, face challenges supporting PoB's update mechanism. To make it work, fragile workarounds had to be implemented that can break unexpectedly)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
+17 -6
View File
@@ -13,9 +13,12 @@ use crate::{
}, },
rendering::PoBString, rendering::PoBString,
search_handle::new_search_handle, search_handle::new_search_handle,
window::{get_screen_scale, get_screen_size, set_foreground, set_window_title}, window::{
get_dpi_scale_override, get_screen_scale, get_screen_size, set_dpi_scale_override,
set_foreground, set_window_title,
},
}, },
lua::ContextSocket, lua::Context,
}; };
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic}; use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic};
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
@@ -88,6 +91,14 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?; globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?; globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
globals.set("SetForeground", lua.create_function(set_foreground)?)?; globals.set("SetForeground", lua.create_function(set_foreground)?)?;
globals.set(
"SetDPIScaleOverridePercent",
lua.create_function(set_dpi_scale_override)?,
)?;
globals.set(
"GetDPIScaleOverridePercent",
lua.create_function(get_dpi_scale_override)?,
)?;
// lua // lua
globals.set("PCall", lua.create_function(protected_call)?)?; globals.set("PCall", lua.create_function(protected_call)?)?;
@@ -118,8 +129,8 @@ fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
} }
fn restart(l: &Lua, _: ()) -> LuaResult<()> { fn restart(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
*socket.needs_restart() = true; *ctx.needs_restart() = true;
Ok(()) Ok(())
} }
@@ -131,10 +142,10 @@ fn open_url(l: &Lua, url: String) -> LuaResult<MultiValue> {
} }
fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> { fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
for feature in features { for feature in features {
if feature == "DPI_AWARE" { if feature == "DPI_AWARE" {
*socket.is_dpi_aware() = true; *ctx.is_dpi_aware() = true;
} }
} }
Ok(()) Ok(())
+5 -5
View File
@@ -1,9 +1,9 @@
use crate::lua::ContextSocket; use crate::lua::Context;
use mlua::{Lua, Result as LuaResult}; use mlua::{Lua, Result as LuaResult};
pub fn copy(l: &Lua, text: String) -> LuaResult<()> { pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
socket ctx
.clipboard() .clipboard()
.set_text(text) .set_text(text)
.map_err(|e| anyhow::anyhow!("{}", e))?; .map_err(|e| anyhow::anyhow!("{}", e))?;
@@ -11,8 +11,8 @@ pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
} }
pub fn paste(l: &Lua, _: ()) -> LuaResult<String> { pub fn paste(l: &Lua, _: ()) -> LuaResult<String> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let text = socket let text = ctx
.clipboard() .clipboard()
.get_text() .get_text()
.map_err(|e| anyhow::anyhow!("{}", e))?; .map_err(|e| anyhow::anyhow!("{}", e))?;
+4 -4
View File
@@ -1,5 +1,5 @@
use crate::{ use crate::{
lua::ContextSocket, lua::Context,
renderer::textures::{TextureHandle, TextureOptions}, renderer::textures::{TextureHandle, TextureOptions},
}; };
use mlua::{Lua, MultiValue, Result as LuaResult, UserData}; use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
@@ -56,7 +56,7 @@ fn load(
handle: &mut ImageHandle, handle: &mut ImageHandle,
(image_path, flags): (String, MultiValue), (image_path, flags): (String, MultiValue),
) -> LuaResult<()> { ) -> LuaResult<()> {
let socket = lua.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = lua.app_data_ref::<&'static Context>().unwrap();
let mut is_async = false; let mut is_async = false;
let mut options = TextureOptions::LINEAR_REPEAT; let mut options = TextureOptions::LINEAR_REPEAT;
@@ -76,7 +76,7 @@ fn load(
// replace image data if already allocated // replace image data if already allocated
ImageHandle::Loaded(texture_handle) => { ImageHandle::Loaded(texture_handle) => {
// in case of error, stay loaded with current texture // in case of error, stay loaded with current texture
let _ = socket.texture_manager().update_texture( let _ = ctx.texture_manager().update_texture(
texture_handle.id(), texture_handle.id(),
image_path, image_path,
options, options,
@@ -85,7 +85,7 @@ fn load(
} }
// create new texture handle // create new texture handle
ImageHandle::Unloaded => { ImageHandle::Unloaded => {
if let Ok(tex_handle) = socket if let Ok(tex_handle) = ctx
.texture_manager() .texture_manager()
.load_texture(image_path, options, is_async) .load_texture(image_path, options, is_async)
{ {
+6 -6
View File
@@ -1,22 +1,22 @@
use crate::{ use crate::{
input::{str_as_keycode, str_as_mousebutton}, input::{str_as_keycode, str_as_mousebutton},
lua::ContextSocket, lua::Context,
}; };
use mlua::{Lua, Result as LuaResult}; use mlua::{Lua, Result as LuaResult};
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let pos = socket.input().mouse_pos(); let pos = ctx.input().mouse_pos();
Ok((pos.x as u32, pos.y as u32)) Ok((pos.x as u32, pos.y as u32))
} }
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> { pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
if let Some(code) = str_as_keycode(&key_name) { if let Some(code) = str_as_keycode(&key_name) {
Ok(socket.input().key_pressed(code)) Ok(ctx.input().key_pressed(code))
} else if let Some(button) = str_as_mousebutton(&key_name) { } else if let Some(button) = str_as_mousebutton(&key_name) {
Ok(socket.input().mouse_pressed(button)) Ok(ctx.input().mouse_pressed(button))
} else { } else {
Ok(false) Ok(false)
} }
+7 -19
View File
@@ -1,26 +1,14 @@
use anyhow::anyhow;
use directories::UserDirs;
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value}; use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::{fs, path::PathBuf}; use std::{fs, path::PathBuf};
use crate::{ use crate::{
args::Game, args::Game,
lua::ContextSocket, lua::Context,
util::{change_working_directory, get_executable_dir}, util::{change_working_directory, get_executable_dir},
}; };
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<anyhow::Result<PathBuf>> { pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
let user_dirs = match UserDirs::new() { Ok(Game::user_data_dir())
Some(user_dirs) => user_dirs,
None => return Ok(Err(anyhow!("Failed to retrieve user's home directory"))),
};
match user_dirs.document_dir() {
Some(docs_dir) => Ok(Ok(docs_dir.canonicalize().unwrap())),
None => Ok(Err(anyhow!(
"Failed to retrieve user's documents directory"
))),
}
} }
// parent directory of Launch.lua script // parent directory of Launch.lua script
@@ -37,15 +25,15 @@ pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
} }
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> { pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(socket.current_working_dir().to_path_buf()) Ok(ctx.current_working_dir().to_path_buf())
} }
// NOTE: unused // NOTE: unused
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> { pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
if change_working_directory(&path).is_ok() { if change_working_directory(&path).is_ok() {
*socket.current_working_dir() = path.into(); *ctx.current_working_dir() = path.into();
} }
Ok(()) Ok(())
} }
+53 -48
View File
@@ -2,8 +2,8 @@ use crate::{
api::image_handle::ImageHandle, api::image_handle::ImageHandle,
color::Srgba, color::Srgba,
dpi::Uv, dpi::Uv,
fonts::{Alignment, LayoutJob}, fonts::{Alignment, FontStyle, LayoutJob},
lua::ContextSocket, lua::Context,
math::{Point, Quad, Rect, Size}, math::{Point, Quad, Rect, Size},
}; };
use core::ffi::{c_int, c_void}; use core::ffi::{c_int, c_void};
@@ -11,8 +11,9 @@ use mlua::{
LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value, LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value,
ffi::{self}, ffi::{self},
}; };
use parley::FontFamily;
use regex::Regex; use regex::Regex;
use std::sync::LazyLock; use std::{borrow::Cow, sync::LazyLock};
pub fn register_globals(lua: &Lua) -> LuaResult<()> { pub fn register_globals(lua: &Lua) -> LuaResult<()> {
let globals = lua.globals(); let globals = lua.globals();
@@ -126,9 +127,7 @@ unsafe extern "C" fn lua_toimghandle(state: *mut ffi::lua_State, idx: c_int) ->
unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_draw_color"); //profiling::scope!("set_draw_color");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
match nargs { match nargs {
@@ -136,7 +135,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
1 => { 1 => {
let esc_str = str_from_stack!(state, -nargs); let esc_str = str_from_stack!(state, -nargs);
let color = Srgba::from_escape_code(esc_str); let color = Srgba::from_escape_code(esc_str);
socket.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
// rgb // rgb
3 => { 3 => {
@@ -144,7 +143,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
let g = f32_from_stack!(state, -nargs + 1); let g = f32_from_stack!(state, -nargs + 1);
let b = f32_from_stack!(state, -nargs + 2); let b = f32_from_stack!(state, -nargs + 2);
let color = Srgba::new_f32(r, g, b, 1.0); let color = Srgba::new_f32(r, g, b, 1.0);
socket.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
// rgba // rgba
4 => { 4 => {
@@ -153,7 +152,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
let b = f32_from_stack!(state, -nargs + 2); let b = f32_from_stack!(state, -nargs + 2);
let a = f32_from_stack!(state, -nargs + 3); let a = f32_from_stack!(state, -nargs + 3);
let color = Srgba::new_f32(r, g, b, a); let color = Srgba::new_f32(r, g, b, a);
socket.layers().set_draw_color(color); ctx.layers().set_draw_color(color);
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; };
@@ -164,22 +163,20 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_viewport"); //profiling::scope!("set_viewport");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
match nargs { match nargs {
0 => socket 0 => ctx
.layers() .layers()
.set_viewport_from_size(socket.window().logical_size()), .set_viewport_from_size(ctx.window().logical_size()),
4 => { 4 => {
let x = f32_from_stack!(state, -nargs); let x = f32_from_stack!(state, -nargs);
let y = f32_from_stack!(state, -nargs + 1); let y = f32_from_stack!(state, -nargs + 1);
let w = f32_from_stack!(state, -nargs + 2); let w = f32_from_stack!(state, -nargs + 2);
let h = f32_from_stack!(state, -nargs + 3); let h = f32_from_stack!(state, -nargs + 3);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h)); let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
socket.layers().set_viewport(rect); ctx.layers().set_viewport(rect);
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
}; };
@@ -190,16 +187,14 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_draw_layer"); //profiling::scope!("set_draw_layer");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
match nargs { match nargs {
1 => { 1 => {
let layer = i32_from_stack!(state, -nargs); let layer = i32_from_stack!(state, -nargs);
socket.layers().set_draw_layer(layer, 0); ctx.layers().set_draw_layer(layer, 0);
} }
2 => { 2 => {
let layer = match unsafe { ffi::lua_type(state, -nargs) } { let layer = match unsafe { ffi::lua_type(state, -nargs) } {
@@ -212,9 +207,9 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
}; };
let sublayer = i32_from_stack!(state, -nargs + 1); let sublayer = i32_from_stack!(state, -nargs + 1);
if let Some(layer) = layer { if let Some(layer) = layer {
socket.layers().set_draw_layer(layer, sublayer); ctx.layers().set_draw_layer(layer, sublayer);
} else { } else {
socket.layers().set_draw_sublayer(sublayer); ctx.layers().set_draw_sublayer(sublayer);
} }
} }
_ => panic!("Unexpected number of arguments"), _ => panic!("Unexpected number of arguments"),
@@ -226,9 +221,7 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image"); //profiling::scope!("draw_image");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) { if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
@@ -268,7 +261,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
0 0
}; };
socket.layers().draw_rect(texture_id, rect, uv, layer_idx); ctx.layers().draw_rect(texture_id, rect, uv, layer_idx);
0 0
} }
@@ -276,9 +269,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image_quad", format!("args: {:?}", args)); //profiling::scope!("draw_image_quad", format!("args: {:?}", args));
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) { if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
@@ -336,7 +327,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
0 0
}; };
socket.layers().draw_quad(texture_id, quad, uv, layer_idx); ctx.layers().draw_quad(texture_id, quad, uv, layer_idx);
0 0
} }
@@ -344,9 +335,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_string"); //profiling::scope!("draw_string");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
@@ -369,7 +358,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
let mut position = Point::new(x, y); let mut position = Point::new(x, y);
let mut is_absolute_position = false; let mut is_absolute_position = false;
// the position needs to be adjusted for some alignments to match PoBs behavior // the position needs to be adjusted for some alignments to match PoBs behavior
let screen_size = socket.window().logical_size(); let screen_size = ctx.window().logical_size();
let halign = match alignment { let halign = match alignment {
PoBTextAlignment::Left => Alignment::Min, PoBTextAlignment::Left => Alignment::Min,
PoBTextAlignment::Center => { PoBTextAlignment::Center => {
@@ -386,7 +375,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
PoBTextAlignment::RightX => Alignment::Max, PoBTextAlignment::RightX => Alignment::Max,
}; };
let current_draw_color = socket.layers().get_draw_color(); let current_draw_color = ctx.layers().get_draw_color();
let job = build_layout_job( let job = build_layout_job(
text, text,
current_draw_color, current_draw_color,
@@ -398,11 +387,11 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
// NOTE: color escape codes modify the current draw color. // NOTE: color escape codes modify the current draw color.
// set current draw color to color of last segment to match PoB's behavior // set current draw color to color of last segment to match PoB's behavior
if let Some(last_segment) = job.segments.last() { if let Some(last_segment) = job.segments.last() {
socket.layers().set_draw_color(last_segment.color); ctx.layers().set_draw_color(last_segment.color);
} }
let layout = socket.fonts().layout(job, socket.window().scale_factor); let layout = ctx.fonts().layout(job, ctx.window().scale_factor);
socket ctx
.layers() .layers()
.draw_text(position, layout, is_absolute_position); .draw_text(position, layout, is_absolute_position);
@@ -412,9 +401,7 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int { unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("get_string_width"); //profiling::scope!("get_string_width");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) }; let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) }; let nargs = unsafe { ffi::lua_gettop(state) };
@@ -428,9 +415,9 @@ unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_in
}; };
let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None); let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None);
let width = socket let width = ctx
.fonts() .fonts()
.get_text_width(job, socket.window().scale_factor); .get_text_width(job, ctx.window().scale_factor);
unsafe { ffi::lua_pushnumber(state, width as f64) }; unsafe { ffi::lua_pushnumber(state, width as f64) };
1 1
@@ -441,15 +428,15 @@ fn get_index_at_cur(
(line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32), (line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32),
) -> LuaResult<usize> { ) -> LuaResult<usize> {
//profiling::scope!("get_char_index_at_cur"); //profiling::scope!("get_char_index_at_cur");
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let font_type = font_type.parse::<PoBFontType>()?; let font_type = font_type.parse::<PoBFontType>()?;
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None); let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
let index = socket.fonts().get_text_index_at_cursor( let index = ctx.fonts().get_text_index_at_cursor(
job, job,
Point::new(cur_x, cur_y), Point::new(cur_x, cur_y),
socket.window().scale_factor, ctx.window().scale_factor,
); );
// convert to lua's 1-based indexing // convert to lua's 1-based indexing
@@ -467,12 +454,21 @@ fn build_layout_job<'a>(
alignment: Option<Alignment>, alignment: Option<Alignment>,
) -> LayoutJob<'a> { ) -> LayoutJob<'a> {
let mut font_weight = None; let mut font_weight = None;
let mut font_style = FontStyle::default();
let font_family = match font_type { let font_family = match font_type {
PoBFontType::Fixed => parley::GenericFamily::Monospace, PoBFontType::Fixed => FontFamily::Named(Cow::Borrowed("Bitstream Vera Sans Mono")),
PoBFontType::Var => parley::GenericFamily::SansSerif, PoBFontType::Var => FontFamily::Named(Cow::Borrowed("Liberation Sans")),
PoBFontType::VarBold => { PoBFontType::VarBold => {
font_weight = Some(700.0); font_weight = Some(700.0);
parley::GenericFamily::SansSerif FontFamily::Named(Cow::Borrowed("Liberation Sans"))
}
PoBFontType::Fontin => FontFamily::Named(Cow::Borrowed("Fontin")),
PoBFontType::FontinItalic => FontFamily::Named(Cow::Borrowed("Fontin")),
PoBFontType::FontinSmallcaps => FontFamily::Named(Cow::Borrowed("Fontin SmallCaps")),
PoBFontType::FontinSmallcapsItalic => {
font_style = FontStyle::Italic;
// use regular Smallcaps with "faux italics"
FontFamily::Named(Cow::Borrowed("Fontin SmallCaps"))
} }
}; };
@@ -485,6 +481,7 @@ fn build_layout_job<'a>(
line_height as f32, line_height as f32,
alignment, alignment,
font_weight, font_weight,
font_style,
); );
for (color, segment) in PoBString(text).into_iter() { for (color, segment) in PoBString(text).into_iter() {
@@ -622,6 +619,10 @@ enum PoBFontType {
Fixed, Fixed,
Var, Var,
VarBold, VarBold,
FontinSmallcaps,
FontinSmallcapsItalic,
Fontin,
FontinItalic,
} }
impl std::str::FromStr for PoBFontType { impl std::str::FromStr for PoBFontType {
@@ -632,6 +633,10 @@ impl std::str::FromStr for PoBFontType {
"FIXED" => Ok(Self::Fixed), "FIXED" => Ok(Self::Fixed),
"VAR" => Ok(Self::Var), "VAR" => Ok(Self::Var),
"VAR BOLD" => Ok(Self::VarBold), "VAR BOLD" => Ok(Self::VarBold),
"FONTIN SC" => Ok(Self::FontinSmallcaps),
"FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic),
"FONTIN" => Ok(Self::Fontin),
"FONTIN ITALIC" => Ok(Self::FontinItalic),
_ => Err(anyhow::anyhow!( _ => Err(anyhow::anyhow!(
"'{}' is not a valid TextFontType variant", "'{}' is not a valid TextFontType variant",
s s
+22 -11
View File
@@ -1,34 +1,45 @@
use crate::{ use crate::{
dpi::{LogicalSize, PhysicalSize}, dpi::{LogicalSize, PhysicalSize},
lua::ContextSocket, lua::Context,
}; };
use mlua::{Lua, Result as LuaResult}; use mlua::{Lua, Result as LuaResult};
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
let size = if *socket.is_dpi_aware() { let size = if *ctx.is_dpi_aware() {
let PhysicalSize { width, height, .. } = socket.window().size; let PhysicalSize { width, height, .. } = ctx.window().size;
(width, height) (width, height)
} else { } else {
let LogicalSize { width, height, .. } = socket.window().logical_size(); let LogicalSize { width, height, .. } = ctx.window().logical_size();
(width, height) (width, height)
}; };
Ok(size) Ok(size)
} }
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> { pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(socket.window().scale_factor) let scale_factor = ctx.window().scale_factor;
Ok(scale_factor)
} }
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> { pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
socket.window().set_window_title(&title); ctx.window().set_window_title(&title);
Ok(()) Ok(())
} }
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> { pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
socket.window().focus(); ctx.window().focus();
Ok(()) Ok(())
} }
pub fn set_dpi_scale_override(_: &Lua, _percent: i32) -> LuaResult<()> {
// TODO:
Ok(())
}
pub fn get_dpi_scale_override(_: &Lua, _: ()) -> LuaResult<i32> {
// TODO:
Ok(0)
}
+89 -3
View File
@@ -1,6 +1,7 @@
use crate::{ use crate::{
args::Game,
dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize}, dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize},
fonts::Fonts, fonts::{FontData, FontDefinitions, Fonts},
gfx::{GraphicsContext, RenderJob}, gfx::{GraphicsContext, RenderJob},
input::InputState, input::InputState,
installer::InstallMode, installer::InstallMode,
@@ -17,6 +18,7 @@ use winit::{
event::*, event::*,
event_loop::ActiveEventLoop, event_loop::ActiveEventLoop,
keyboard::{ModifiersState, PhysicalKey}, keyboard::{ModifiersState, PhysicalKey},
platform::wayland::WindowAttributesExtWayland,
window::Window, window::Window,
}; };
@@ -54,7 +56,7 @@ impl App {
state: AppState { state: AppState {
window: WindowState::default(), window: WindowState::default(),
input: InputState::default(), input: InputState::default(),
fonts: Fonts::new(), fonts: Fonts::new(pob_font_definitions()),
texture_manager: WrappedTextureManager::new(), texture_manager: WrappedTextureManager::new(),
clipboard: arboard::Clipboard::new()?, clipboard: arboard::Clipboard::new()?,
}, },
@@ -123,7 +125,19 @@ impl App {
impl ApplicationHandler<GraphicsContext> for App { impl ApplicationHandler<GraphicsContext> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) { fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = match event_loop.create_window(Window::default_attributes()) { let (title, app_id) = match Game::current() {
Game::Poe1 => ("Path of Building 1", "rusty-path-of-building-1"),
Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"),
};
let window_attributes = Window::default_attributes()
.with_title(title)
.with_window_icon(load_icon()) // only works on windows and x11
// on wayland we need an `app_id` that matches the name of a `.desktop` entry to load
// the icon
.with_name(app_id, app_id);
let window = match event_loop.create_window(window_attributes) {
Ok(window) => Arc::new(window), Ok(window) => Arc::new(window),
Err(err) => { Err(err) => {
log::error!("{err}"); log::error!("{err}");
@@ -277,3 +291,75 @@ impl ApplicationHandler<GraphicsContext> for App {
} }
} }
} }
fn pob_font_definitions() -> FontDefinitions {
let mut definitions = FontDefinitions::default();
definitions.font_data.insert(
"bitstream-vera-sans-mono".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/VeraMono.ttf"
))),
);
definitions.font_data.insert(
"liberation-sans".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/LiberationSans-Regular.ttf"
))),
);
definitions.font_data.insert(
"liberation-sans-bold".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/LiberationSans-Bold.ttf"
))),
);
definitions.font_data.insert(
"fontin-regular".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/fontin-regular.ttf"
))),
);
definitions.font_data.insert(
"fontin-italic".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/fontin-italic.ttf"
))),
);
definitions.font_data.insert(
"fontin-smallcaps".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../fonts/fontin-smallcaps.ttf"
))),
);
definitions.generic_families.insert(
parley::GenericFamily::Monospace,
vec!["bitstream-vera-sans-mono".to_owned()],
);
definitions.generic_families.insert(
parley::GenericFamily::SansSerif,
vec![
"liberation-sans".to_owned(),
"liberation-sans-bold".to_owned(),
],
);
definitions.generic_families.insert(
parley::GenericFamily::Serif,
vec![
"fontin-regular".to_owned(),
"fontin-italic".to_owned(),
"fontin-smallcaps".to_owned(),
],
);
definitions
}
fn load_icon() -> Option<winit::window::Icon> {
let image_data = include_bytes!("../assets/icon.png");
let image = image::load_from_memory(image_data).ok()?.into_rgba8();
let (width, height) = image.dimensions();
winit::window::Icon::from_rgba(image.into_raw(), width, height).ok()
}
+9 -1
View File
@@ -31,11 +31,19 @@ impl Game {
GAME_CONFIG.get().expect("Game should be initialized") GAME_CONFIG.get().expect("Game should be initialized")
} }
pub fn script_dir() -> PathBuf { pub fn data_dir() -> PathBuf {
let directory_name = match Self::current() { let directory_name = match Self::current() {
Game::Poe1 => "RustyPathOfBuilding1", Game::Poe1 => "RustyPathOfBuilding1",
Game::Poe2 => "RustyPathOfBuilding2", Game::Poe2 => "RustyPathOfBuilding2",
}; };
BaseDirs::new().unwrap().data_dir().join(directory_name) BaseDirs::new().unwrap().data_dir().join(directory_name)
} }
pub fn script_dir() -> PathBuf {
Game::data_dir()
}
pub fn user_data_dir() -> PathBuf {
Game::data_dir().join("userdata")
}
} }
+49 -42
View File
@@ -7,24 +7,24 @@ use crate::{
renderer::image::ImageDelta, renderer::image::ImageDelta,
util::calculate_hash, util::calculate_hash,
}; };
use ahash::HashMap;
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
use parley::{ use parley::{
FontContext, FontWeight, GenericFamily, LayoutContext, StyleProperty, TextStyle, fontique::Blob, FontContext, FontFamily, FontStack, FontWeight, GenericFamily, LayoutContext, StyleProperty,
TextStyle, fontique::Blob,
}; };
use std::sync::Arc; use std::sync::Arc;
pub use atlas::FontAtlasSize; pub use atlas::FontAtlasSize;
pub use layout::{Alignment, Layout, LayoutJob}; pub use layout::{Alignment, FontStyle, Layout, LayoutJob};
mod atlas; mod atlas;
mod glyph_key; mod glyph_key;
mod layout; mod layout;
mod rasterizer; mod rasterizer;
pub const BITSTREAM_VERA_SANS_MONO: &[u8] = include_bytes!("../fonts/VeraMono.ttf"); /// Data of a .ttf or .otf file
pub const LIBERATION_SANS: &[u8] = include_bytes!("../fonts/LiberationSans-Regular.ttf"); #[derive(Clone, Debug)]
pub const LIBERATION_SANS_BOLD: &[u8] = include_bytes!("../fonts/LiberationSans-Bold.ttf");
pub struct FontData { pub struct FontData {
data: std::borrow::Cow<'static, [u8]>, data: std::borrow::Cow<'static, [u8]>,
} }
@@ -43,13 +43,14 @@ impl AsRef<[u8]> for FontData {
} }
} }
pub struct FontDefinition { #[derive(Clone, Debug, Default)]
pub generic_families: Vec<GenericFamily>, pub struct FontDefinitions {
pub data: Arc<FontData>, pub font_data: HashMap<String, Arc<FontData>>,
pub generic_families: HashMap<GenericFamily, Vec<String>>,
} }
pub struct Fonts { pub struct Fonts {
font_definitions: Vec<FontDefinition>, definitions: FontDefinitions,
font_context: FontContext, font_context: FontContext,
layout_context: LayoutContext<Srgba>, layout_context: LayoutContext<Srgba>,
atlas: FontAtlas, atlas: FontAtlas,
@@ -58,25 +59,9 @@ pub struct Fonts {
} }
impl Fonts { impl Fonts {
pub fn new() -> Self { pub fn new(definitions: FontDefinitions) -> Self {
// add fonts used by PoB
let font_definitions = vec![
FontDefinition {
generic_families: vec![GenericFamily::Monospace],
data: Arc::new(FontData::from_static(BITSTREAM_VERA_SANS_MONO)),
},
FontDefinition {
generic_families: vec![GenericFamily::SansSerif],
data: Arc::new(FontData::from_static(LIBERATION_SANS)),
},
FontDefinition {
generic_families: vec![GenericFamily::SansSerif],
data: Arc::new(FontData::from_static(LIBERATION_SANS_BOLD)),
},
];
let mut fonts = Self { let mut fonts = Self {
font_definitions, definitions,
font_context: FontContext::new(), font_context: FontContext::new(),
layout_context: LayoutContext::new(), layout_context: LayoutContext::new(),
atlas: FontAtlas::new(1024), atlas: FontAtlas::new(1024),
@@ -92,14 +77,20 @@ impl Fonts {
} }
fn register_fonts(&mut self) { fn register_fonts(&mut self) {
for definition in &self.font_definitions { for data in self.definitions.font_data.values() {
let blob = Blob::new(Arc::new(definition.data.data.clone())); let blob = Blob::new(Arc::new(data.data.clone()));
let registered_fonts = self.font_context.collection.register_fonts(blob, None); self.font_context.collection.register_fonts(blob, None);
for generic_family in &definition.generic_families { }
self.font_context
.collection for (generic_family, family_fonts) in &self.definitions.generic_families {
.append_generic_families(*generic_family, registered_fonts.iter().map(|f| f.0)); let family_ids: Vec<_> = family_fonts
} .iter()
.filter_map(|family_name| self.font_context.collection.family_id(family_name))
.collect();
self.font_context
.collection
.set_generic_families(*generic_family, family_ids.into_iter());
} }
} }
@@ -128,13 +119,26 @@ impl Fonts {
common_chars.push(c as char); common_chars.push(c as char);
} }
self.preload_text(&common_chars, font_size, GenericFamily::Monospace, None);
self.preload_text(&common_chars, font_size, GenericFamily::SansSerif, None);
self.preload_text( self.preload_text(
&common_chars, &common_chars,
font_size, font_size,
GenericFamily::SansSerif, FontFamily::Generic(GenericFamily::Monospace),
None,
parley::FontStyle::Normal,
);
self.preload_text(
&common_chars,
font_size,
FontFamily::Generic(GenericFamily::SansSerif),
None,
parley::FontStyle::Normal,
);
self.preload_text(
&common_chars,
font_size,
FontFamily::Generic(GenericFamily::SansSerif),
Some(FontWeight::BOLD), Some(FontWeight::BOLD),
parley::FontStyle::Normal,
); );
} }
@@ -142,14 +146,16 @@ impl Fonts {
&mut self, &mut self,
text: &str, text: &str,
font_size: f32, font_size: f32,
generic_family: GenericFamily, font_family: FontFamily,
font_weight: Option<FontWeight>, font_weight: Option<FontWeight>,
font_style: parley::FontStyle,
) { ) {
profiling::scope!("preload_text"); profiling::scope!("preload_text");
let style = TextStyle { let style = TextStyle {
font_stack: parley::FontStack::Single(parley::FontFamily::Generic(generic_family)), font_stack: FontStack::Single(font_family),
font_weight: font_weight.unwrap_or(FontWeight::NORMAL), font_weight: font_weight.unwrap_or(FontWeight::NORMAL),
font_style,
font_size, font_size,
..Default::default() ..Default::default()
}; };
@@ -194,13 +200,14 @@ impl Fonts {
let default_style = TextStyle::default(); let default_style = TextStyle::default();
let style = TextStyle { let style = TextStyle {
font_stack: parley::FontStack::Single(parley::FontFamily::Generic(job.font_family)), font_stack: parley::FontStack::Single(job.font_family),
font_size: job.font_size.into(), font_size: job.font_size.into(),
line_height: parley::LineHeight::Absolute(job.line_height.into()), line_height: parley::LineHeight::Absolute(job.line_height.into()),
font_weight: job font_weight: job
.font_weight .font_weight
.map(|w| parley::FontWeight::new(w.into())) .map(|w| parley::FontWeight::new(w.into()))
.unwrap_or(default_style.font_weight), .unwrap_or(default_style.font_weight),
font_style: job.font_style.into(),
..default_style ..default_style
}; };
+44 -5
View File
@@ -1,37 +1,56 @@
use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph}; use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph};
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
use parley::GenericFamily; use parley::FontFamily;
#[derive(Copy, Clone, Debug, Hash)] #[derive(Copy, Clone, Default, Debug, Hash, PartialEq)]
pub enum Alignment { pub enum Alignment {
#[default]
Min, Min,
Center, Center,
Max, Max,
} }
#[derive(Copy, Clone, Default, Debug, Hash, PartialEq)]
pub enum FontStyle {
#[default]
Normal,
Italic,
}
impl From<FontStyle> for parley::FontStyle {
fn from(value: FontStyle) -> Self {
match value {
FontStyle::Normal => parley::FontStyle::Normal,
FontStyle::Italic => parley::FontStyle::Italic,
}
}
}
#[derive(Clone, Debug, Hash)] #[derive(Clone, Debug, Hash)]
pub struct LayoutSegment<'s> { pub struct LayoutSegment<'s> {
pub text: &'s str, pub text: &'s str,
pub color: Srgba, pub color: Srgba,
} }
#[derive(Clone, Debug, Hash)] #[derive(Clone, Debug)]
pub struct LayoutJob<'s> { pub struct LayoutJob<'s> {
pub segments: Vec<LayoutSegment<'s>>, pub segments: Vec<LayoutSegment<'s>>,
pub font_family: GenericFamily, pub font_family: FontFamily<'static>,
pub font_size: OrderedFloat<f32>, pub font_size: OrderedFloat<f32>,
pub line_height: OrderedFloat<f32>, pub line_height: OrderedFloat<f32>,
pub alignment: Option<Alignment>, pub alignment: Option<Alignment>,
pub font_weight: Option<OrderedFloat<f32>>, pub font_weight: Option<OrderedFloat<f32>>,
pub font_style: FontStyle,
} }
impl<'s> LayoutJob<'s> { impl<'s> LayoutJob<'s> {
pub fn new( pub fn new(
font_family: GenericFamily, font_family: FontFamily<'static>,
font_size: f32, font_size: f32,
line_height: f32, line_height: f32,
alignment: Option<Alignment>, alignment: Option<Alignment>,
font_weight: Option<f32>, font_weight: Option<f32>,
font_style: FontStyle,
) -> Self { ) -> Self {
Self { Self {
segments: Vec::new(), segments: Vec::new(),
@@ -40,6 +59,7 @@ impl<'s> LayoutJob<'s> {
line_height: line_height.into(), line_height: line_height.into(),
alignment, alignment,
font_weight: font_weight.map(OrderedFloat), font_weight: font_weight.map(OrderedFloat),
font_style,
} }
} }
@@ -48,6 +68,25 @@ impl<'s> LayoutJob<'s> {
} }
} }
impl std::hash::Hash for LayoutJob<'_> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.segments.hash(state);
match &self.font_family {
FontFamily::Named(cow) => {
cow.hash(state);
}
FontFamily::Generic(generic_family) => {
generic_family.hash(state);
}
}
self.font_size.hash(state);
self.line_height.hash(state);
self.alignment.hash(state);
self.font_weight.hash(state);
self.font_style.hash(state);
}
}
#[derive(Default)] #[derive(Default)]
pub struct LayoutRow { pub struct LayoutRow {
pub glyphs: Vec<RasterizedGlyph>, pub glyphs: Vec<RasterizedGlyph>,
+23 -4
View File
@@ -14,6 +14,7 @@ use image::GenericImage;
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
use parley::{FontData, GlyphRun}; use parley::{FontData, GlyphRun};
use std::borrow::Cow; use std::borrow::Cow;
use swash::zeno;
type FontBlobId = u64; type FontBlobId = u64;
type FontIndex = u32; type FontIndex = u32;
@@ -25,14 +26,21 @@ struct StyleKey<'a> {
font_blob_id: FontBlobId, font_blob_id: FontBlobId,
font_size: OrderedFloat<f32>, font_size: OrderedFloat<f32>,
normalized_coords: Cow<'a, [i16]>, normalized_coords: Cow<'a, [i16]>,
skew: i8,
} }
impl<'a> StyleKey<'a> { impl<'a> StyleKey<'a> {
fn new(font_blob_id: FontBlobId, font_size: f32, normalized_coords: &'a [i16]) -> Self { fn new(
font_blob_id: FontBlobId,
font_size: f32,
normalized_coords: &'a [i16],
skew: i8,
) -> Self {
Self { Self {
font_blob_id, font_blob_id,
font_size: font_size.into(), font_size: font_size.into(),
normalized_coords: Cow::Borrowed(normalized_coords), normalized_coords: Cow::Borrowed(normalized_coords),
skew,
} }
} }
@@ -135,8 +143,9 @@ impl GlyphRasterizer {
font_data: &FontData, font_data: &FontData,
font_size: f32, font_size: f32,
norm_coords: &[i16], norm_coords: &[i16],
skew: i8,
) -> StyleId { ) -> StyleId {
let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords); let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords, skew);
match self.style_ids.get(&style_key) { match self.style_ids.get(&style_key) {
Some(key) => *key, Some(key) => *key,
None => *self None => *self
@@ -164,9 +173,16 @@ impl GlyphRasterizer {
let color = glyph_run.style().brush; let color = glyph_run.style().brush;
let font_size = run.font_size() * pixels_per_point; let font_size = run.font_size() * pixels_per_point;
let normalized_coords = run.normalized_coords(); let normalized_coords = run.normalized_coords();
let skew = run.synthesis().skew(); // skew angle for faux italic
let font_ref = self.get_font_ref(run.font()); let font_ref = self.get_font_ref(run.font());
let style_id = self.get_style_id(run.font(), font_size, normalized_coords); let style_id = self.get_style_id(
run.font(),
font_size,
normalized_coords,
// parley stores skew as i8 internally so this conversion is ok
skew.unwrap_or_default() as i8,
);
let mut scaler = self let mut scaler = self
.scale_context .scale_context
@@ -198,7 +214,10 @@ impl GlyphRasterizer {
swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit), swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
swash::scale::Source::Outline, swash::scale::Source::Outline,
]) ])
.format(swash::zeno::Format::Alpha) .format(zeno::Format::Alpha)
.transform(skew.map(|skew| {
zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)
}))
.offset(fract_offset) .offset(fract_offset)
.render_into(&mut scaler, glyph.id as u16, image); .render_into(&mut scaler, glyph.id as u16, image);
+1 -1
View File
@@ -95,7 +95,7 @@ impl GraphicsContext {
let surface_format = surface_caps let surface_format = surface_caps
.formats .formats
.iter() .iter()
.find(|f| !f.is_srgb()) .find(|f| !f.is_srgb() && f.required_features().is_empty())
.copied() .copied()
.unwrap_or(surface_caps.formats[0]); .unwrap_or(surface_caps.formats[0]);
+120 -8
View File
@@ -3,20 +3,23 @@ use crate::{
args::Game, args::Game,
color::Srgba, color::Srgba,
dpi::{LogicalPoint, LogicalRect}, dpi::{LogicalPoint, LogicalRect},
fonts::{Alignment, LayoutJob}, fonts::{Alignment, FontStyle, LayoutJob},
mode::{AppEvent, ModeFrameOutput, ModeTransition}, mode::{AppEvent, ModeFrameOutput, ModeTransition},
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive}, renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
}; };
use anyhow::bail; use anyhow::bail;
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use parley::{FontFamily, GenericFamily};
use regex::Regex; use regex::Regex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{ use std::{
fs::{self}, fs::{self},
io::{Write, copy}, io::copy,
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::mpsc::{self, Receiver, TryRecvError}, sync::mpsc::{self, Receiver, TryRecvError},
thread, thread,
}; };
use ureq::http::Response;
const REPO_NAME: &str = "meehl/rusty-pob-manifest"; const REPO_NAME: &str = "meehl/rusty-pob-manifest";
@@ -112,11 +115,12 @@ impl InstallMode {
app_state: &mut AppState, app_state: &mut AppState,
) -> Box<dyn Iterator<Item = ClippedPrimitive>> { ) -> Box<dyn Iterator<Item = ClippedPrimitive>> {
let mut job = LayoutJob::new( let mut job = LayoutJob::new(
parley::GenericFamily::SansSerif, FontFamily::Generic(GenericFamily::SansSerif),
32.0, 32.0,
34.0, 34.0,
Some(Alignment::Center), Some(Alignment::Center),
Some(700.0), Some(700.0),
FontStyle::Normal,
); );
let progress_text = match &self.current_progress { let progress_text = match &self.current_progress {
@@ -158,6 +162,14 @@ fn install<P: AsRef<Path>>(
// Skip installation if version file exists // Skip installation if version file exists
let version_file_path = target_dir.as_ref().join("rpob.version"); let version_file_path = target_dir.as_ref().join("rpob.version");
if version_file_path.exists() { if version_file_path.exists() {
let old_version = fs::read_to_string(&version_file_path).unwrap();
let current_version = env!("CARGO_PKG_VERSION");
if old_version != current_version {
log::info!("New version detected: {old_version} -> {current_version}");
fs::write(&version_file_path, current_version).unwrap();
}
return Ok(()); return Ok(());
} }
@@ -166,9 +178,7 @@ fn install<P: AsRef<Path>>(
set_branch_and_platform(&target_dir)?; set_branch_and_platform(&target_dir)?;
// write version file // write version file
let mut version_file = fs::File::create(version_file_path)?; fs::write(&version_file_path, env!("CARGO_PKG_VERSION")).unwrap();
let pkg_version = env!("CARGO_PKG_VERSION");
version_file.write_all(pkg_version.as_bytes())?;
Ok(()) Ok(())
} }
@@ -189,7 +199,7 @@ fn download_path_of_building<P: AsRef<Path>>(
repo repo
); );
let mut response = ureq::get(url).call()?; let mut response = http_get_with_backoff(&url)?;
let total_size = response let total_size = response
.headers() .headers()
.get("Content-Length") .get("Content-Length")
@@ -293,7 +303,7 @@ fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()>
} }
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> { fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
let mut response = ureq::get(url).call()?; let mut response = http_get_with_backoff(url)?;
if response.status().is_success() { if response.status().is_success() {
let body = response.body_mut(); let body = response.body_mut();
@@ -320,3 +330,105 @@ fn format_bytes(size_in_bytes: u64) -> String {
format!("{} bytes", size_in_bytes) format!("{} bytes", size_in_bytes)
} }
} }
/// Calculates wait time based on rate limit headers or falls back to default backoff.
fn calculate_wait_time(resp: &Response<ureq::Body>, default_backoff: u64) -> u64 {
let headers = resp.headers();
// Wait for time specified in retry-after response header if present
if let Some(retry_after) = headers
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
return retry_after;
}
// The number of requests remaining in the current rate limit window
let remaining = headers
.get("x-ratelimit-remaining")
.and_then(|v| v.to_str().ok());
if remaining == Some("0") {
// Calculate time until rate limit reset
if let Some(reset_epoch) = headers
.get("x-ratelimit-reset")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
let now_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if reset_epoch > now_epoch {
return reset_epoch - now_epoch;
}
}
}
default_backoff
}
/// Performs a GET request with exponential backoff aware of GitHub rate limit headers.
fn http_get_with_backoff(url: &str) -> anyhow::Result<Response<ureq::Body>> {
const MAX_ATTEMPTS: usize = 6;
const MAX_BACKOFF_SECS: u64 = 60;
let mut attempt = 0;
let mut backoff_secs: u64 = 2;
loop {
attempt += 1;
let resp_result = ureq::get(url)
.header("User-Agent", "rusty-path-of-building")
.call();
let resp = match resp_result {
Ok(r) => r,
Err(err) => {
log::warn!(
"Transport error: {} (attempt {}/{})",
err,
attempt,
MAX_ATTEMPTS
);
if attempt >= MAX_ATTEMPTS {
return Err(anyhow::Error::new(err));
}
thread::sleep(Duration::from_secs(backoff_secs));
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
continue;
}
};
let status = resp.status();
if status == 403 || status == 429 {
let wait = calculate_wait_time(&resp, backoff_secs);
log::warn!(
"Rate limited (status {}). Waiting {}s before retry (attempt {}/{})",
status,
wait,
attempt,
MAX_ATTEMPTS
);
if attempt >= MAX_ATTEMPTS {
return Err(anyhow::anyhow!(
"HTTP {} after {} attempts for {}",
status,
attempt,
url
));
}
thread::sleep(Duration::from_secs(wait));
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
continue;
}
if status.is_client_error() || status.is_server_error() {
return Err(anyhow::anyhow!("http status: {} for {}", status, url));
}
return Ok(resp);
}
}
+27 -27
View File
@@ -21,7 +21,7 @@ use std::{
rc::Rc, rc::Rc,
}; };
macro_rules! socket_accessor { macro_rules! ctx_accessor {
($field:ident: & $ty:ty) => { ($field:ident: & $ty:ty) => {
pub fn $field(&self) -> &$ty { pub fn $field(&self) -> &$ty {
let ptr = self.$field.get(); let ptr = self.$field.get();
@@ -42,9 +42,9 @@ macro_rules! socket_accessor {
/// A collection of pointers needed by the API funtions. /// A collection of pointers needed by the API funtions.
/// ///
/// Before executing any lua code, we need to "plug" the [`PoBContext`] into /// Before executing any lua code, we need to "plug" the references into
/// the ContextSocket and "unplug" them afterwards. /// the Context and "unplug" them afterwards.
pub struct ContextSocket { pub struct Context {
window: Cell<*const WindowState>, window: Cell<*const WindowState>,
input: Cell<*const InputState>, input: Cell<*const InputState>,
fonts: Cell<*mut Fonts>, fonts: Cell<*mut Fonts>,
@@ -56,7 +56,7 @@ pub struct ContextSocket {
is_dpi_aware: Cell<*mut bool>, is_dpi_aware: Cell<*mut bool>,
} }
impl ContextSocket { impl Context {
pub fn new() -> &'static Self { pub fn new() -> &'static Self {
Box::leak(Box::new(Self { Box::leak(Box::new(Self {
window: Cell::new(std::ptr::null()), window: Cell::new(std::ptr::null()),
@@ -96,15 +96,15 @@ impl ContextSocket {
self.is_dpi_aware.set(std::ptr::null_mut()); self.is_dpi_aware.set(std::ptr::null_mut());
} }
socket_accessor!(window: &WindowState); ctx_accessor!(window: &WindowState);
socket_accessor!(input: &InputState); ctx_accessor!(input: &InputState);
socket_accessor!(fonts: &mut Fonts); ctx_accessor!(fonts: &mut Fonts);
socket_accessor!(texture_manager: &mut WrappedTextureManager); ctx_accessor!(texture_manager: &mut WrappedTextureManager);
socket_accessor!(clipboard: &mut Clipboard); ctx_accessor!(clipboard: &mut Clipboard);
socket_accessor!(current_working_dir: &mut PathBuf); ctx_accessor!(current_working_dir: &mut PathBuf);
socket_accessor!(layers: &mut Layers); ctx_accessor!(layers: &mut Layers);
socket_accessor!(needs_restart: &mut bool); ctx_accessor!(needs_restart: &mut bool);
socket_accessor!(is_dpi_aware: &mut bool); ctx_accessor!(is_dpi_aware: &mut bool);
} }
pub enum PoBEvent { pub enum PoBEvent {
@@ -183,9 +183,9 @@ impl LuaInstance {
Self::register_package_paths(&lua)?; Self::register_package_paths(&lua)?;
// register "socket" // register context
let socket = ContextSocket::new(); let ctx = Context::new();
lua.set_app_data(socket); lua.set_app_data(ctx);
// register callbacks // register callbacks
api::register_globals(&lua)?; api::register_globals(&lua)?;
@@ -194,15 +194,15 @@ impl LuaInstance {
} }
/// Loads and executes PoB's Launch.lua script /// Loads and executes PoB's Launch.lua script
pub fn launch(&self, ctx: &mut PoBContext) -> LuaResult<()> { pub fn launch(&self, pob_ctx: &mut PoBContext) -> LuaResult<()> {
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
socket.set(ctx); ctx.set(pob_ctx);
let script_dir = Game::script_dir(); let script_dir = Game::script_dir();
change_working_directory(script_dir.as_path())?; change_working_directory(script_dir.as_path())?;
self.load(script_dir.join("Launch.lua")).exec()?; self.load(script_dir.join("Launch.lua")).exec()?;
socket.clear(); ctx.clear();
Ok(()) Ok(())
} }
@@ -234,12 +234,12 @@ impl LuaInstance {
} }
} }
pub fn handle_event(&self, event: PoBEvent, ctx: &mut PoBContext) -> LuaResult<()> { pub fn handle_event(&self, event: PoBEvent, pob_ctx: &mut PoBContext) -> LuaResult<()> {
profiling::scope!("handle_event", format!("{}", event)); profiling::scope!("handle_event", format!("{}", event));
// "Plug" references into "socket" // "Plug" references into context
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap(); let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
socket.set(ctx); ctx.set(pob_ctx);
// Call event handler in PoB application code // Call event handler in PoB application code
let handler_result = match event { let handler_result = match event {
@@ -259,8 +259,8 @@ impl LuaInstance {
} }
}; };
// "Unplug" references from "socket" // "Unplug" references from context
socket.clear(); ctx.clear();
handler_result handler_result
} }
+4
View File
@@ -121,9 +121,13 @@ impl PoBMode {
} }
AppEvent::MouseWheel { delta } => { AppEvent::MouseWheel { delta } => {
if delta > 0.0 { if delta > 0.0 {
self.lua_instance
.handle_event(PoBEvent::KeyDown("WHEELUP", false), &mut ctx)?;
self.lua_instance self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELUP"), &mut ctx)?; .handle_event(PoBEvent::KeyUp("WHEELUP"), &mut ctx)?;
} else if delta < 0.0 { } else if delta < 0.0 {
self.lua_instance
.handle_event(PoBEvent::KeyDown("WHEELDOWN", false), &mut ctx)?;
self.lua_instance self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELDOWN"), &mut ctx)?; .handle_event(PoBEvent::KeyUp("WHEELDOWN"), &mut ctx)?;
} }
+3
View File
@@ -28,6 +28,9 @@ impl WindowState {
window.set_title(&title); window.set_title(&title);
} }
let winit::dpi::PhysicalSize { width, height } = window.inner_size();
self.size = PhysicalSize::new(width, height);
self.scale_factor = window.scale_factor() as f32;
self.window = Some(window); self.window = Some(window);
} }