Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a858af2c38 | ||
|
|
7fc3e340e7 | ||
|
|
dadf5c8804 | ||
|
|
031df6ed9c | ||
|
|
e395e729e8 | ||
|
|
76b5449bad | ||
|
|
f9f05aad08 | ||
|
|
3eacd43837 | ||
|
|
523d5ffe29 | ||
|
|
e18623edb4 | ||
|
|
1812edcbe9 | ||
|
|
df06c8f9c6 | ||
|
|
ae6a24f82c | ||
|
|
0066a05e13 | ||
|
|
3d8143c4d1 | ||
|
|
a3ef4b39d0 | ||
|
|
f48ab50633 | ||
|
|
b86486d5aa | ||
|
|
1f1a331cc2 | ||
|
|
27b93c4a9d | ||
|
|
c95514036f |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Contributing to Rusty Path Of Building
|
||||
|
||||
## Reporting bugs
|
||||
- Ensure the bug was not already reported by searching through existing [issues](https://github.com/meehl/rusty-path-of-building/issues).
|
||||
- If the bug can also be reproduced with the official runtime (e.g. by running through wine), please open an issue in the [PoB1](https://github.com/PathOfBuildingCommunity/PathOfBuilding) or [PoB2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2) repo instead. If you're unsure, feel free to just open it here.
|
||||
- If possible, use the bug report template to create the issue and provide as much information as possible.
|
||||
|
||||
## Contributing code
|
||||
- Get familiar with the code base before you start. I'll try to add more documentation providing a high-level overview of the architecture in the future. Until then, feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
|
||||
- If you intend to work on the API functions, also check out the [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) code base. A great place to ask questions about it is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
|
||||
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A description of what you expected to happen.
|
||||
|
||||
**System information:**
|
||||
- OS: [e.g. Linux, Windows, macOS]
|
||||
- Desktop Environment/Compositor: [e.g. KDE, Gnome, sway, etc.] (only on Linux)
|
||||
- Rusty Path of Building Version: [e.g. v0.2.8]
|
||||
- Path of Building Version: [e.g. PoB1 v2.59.0 or PoB2 v0.12.2]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here. Feel free to add screenshots or any other info like PoB build codes if relevant.
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: yes
|
||||
contact_links:
|
||||
- name: GitHub Discussions
|
||||
url: https://github.com/meehl/rusty-path-of-building/discussions
|
||||
about: Please ask questions unrelated to actual bugs/issues here.
|
||||
+28
-1
@@ -2,6 +2,31 @@
|
||||
|
||||
## [Unreleased] - ReleaseDate
|
||||
|
||||
## [0.2.10] - 2025-12-15
|
||||
|
||||
### Added
|
||||
|
||||
- Implement GetDrawColor
|
||||
|
||||
### Fixed
|
||||
|
||||
- Avoid redundant update after initial download
|
||||
|
||||
## [0.2.9] - 2025-12-03
|
||||
|
||||
### Added
|
||||
|
||||
- Implement UI scale overriding
|
||||
|
||||
### Changed
|
||||
|
||||
- Reduce CPU usage while window is unfocused and not hovered over
|
||||
- Download highest compatible PoB version instead of latest version
|
||||
|
||||
### Fixed
|
||||
|
||||
- Register `AbortSubscript` function under right name
|
||||
|
||||
## [0.2.8] - 2025-11-07
|
||||
|
||||
### Changed
|
||||
@@ -118,8 +143,10 @@
|
||||
- First release
|
||||
|
||||
<!-- next-url -->
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.8...HEAD
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.10...HEAD
|
||||
|
||||
[0.2.10]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.9...v0.2.10
|
||||
[0.2.9]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.8...v0.2.9
|
||||
[0.2.8]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.7...v0.2.8
|
||||
[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
|
||||
|
||||
Generated
+1
-1
@@ -2506,7 +2506,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
|
||||
|
||||
[[package]]
|
||||
name = "rusty-path-of-building"
|
||||
version = "0.2.8"
|
||||
version = "0.2.10"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"anyhow",
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ authors = ["meehl"]
|
||||
description = "Cross-platform runtime for Path of Building"
|
||||
repository = "https://github.com/meehl/rusty-path-of-building"
|
||||
license = "MIT"
|
||||
version = "0.2.8"
|
||||
version = "0.2.10"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@ Please check [the Arch Wiki](https://wiki.archlinux.org/title/Arch_User_Reposito
|
||||
|
||||
[](https://flathub.org/en/apps/community.pathofbuilding.PathOfBuilding)
|
||||
|
||||
### Nix
|
||||
|
||||
[nixpkgs](https://search.nixos.org/packages?type=packages&query=rusty-path-of-building)
|
||||
|
||||
### Building from source
|
||||
|
||||
`LuaJIT` needs to be installed on your system for the `mlua` crate to compile.
|
||||
@@ -43,5 +47,4 @@ Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.ht
|
||||
|
||||
## Known Issues
|
||||
|
||||
- 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)
|
||||
@@ -646,7 +646,7 @@ static int l_zipFile_Read(lua_State* L)
|
||||
if (n < 1) {
|
||||
luaL_error(L, "Usage: zipFile:Read(count) or zipFile:read(\"*a\")");
|
||||
}
|
||||
int count;
|
||||
int count = 0;
|
||||
if (lua_isnumber(L, 1)) {
|
||||
count = lua_tointeger(L, 1);
|
||||
} else {
|
||||
|
||||
+7
-5
@@ -1,4 +1,4 @@
|
||||
use crate::{args::Game, util::change_working_directory};
|
||||
use crate::{lua::Context, util::change_working_directory};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::env;
|
||||
|
||||
@@ -12,26 +12,28 @@ pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResul
|
||||
}
|
||||
|
||||
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let mut module_path = Game::script_dir().join(name);
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let mut module_path = ctx.script_dir().join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(Game::script_dir().as_path())?;
|
||||
change_working_directory(ctx.script_dir().as_path())?;
|
||||
let result = l.load(module_path).call::<MultiValue>(args);
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
|
||||
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let mut module_path = Game::script_dir().join(name);
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let mut module_path = ctx.script_dir().join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(Game::script_dir().as_path())?;
|
||||
change_working_directory(ctx.script_dir().as_path())?;
|
||||
let result = match l.load(module_path).call::<MultiValue>(args) {
|
||||
// on success, callers expect a Nil followed by return values
|
||||
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
|
||||
|
||||
+6
-5
@@ -2,18 +2,19 @@ use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use crate::{
|
||||
args::Game,
|
||||
lua::Context,
|
||||
util::{change_working_directory, get_executable_dir},
|
||||
};
|
||||
|
||||
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
Ok(Game::user_data_dir())
|
||||
pub fn get_user_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
Ok(ctx.script_dir().join("userdata"))
|
||||
}
|
||||
|
||||
// parent directory of Launch.lua script
|
||||
pub fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
Ok(Game::script_dir())
|
||||
pub fn get_script_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
Ok(ctx.script_dir().to_owned())
|
||||
}
|
||||
|
||||
// parent directory of executable
|
||||
|
||||
+19
-7
@@ -34,6 +34,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
// thousands of times per frame. C functions are used to get raw access to
|
||||
// the lua stack without the overhead.
|
||||
unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? };
|
||||
unsafe { globals.set("GetDrawColor", lua.create_c_function(get_draw_color)?)? };
|
||||
unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? };
|
||||
unsafe {
|
||||
globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?;
|
||||
@@ -160,6 +161,20 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_draw_color");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let color: [f32; 4] = ctx.layers().get_draw_color().into();
|
||||
unsafe { ffi::lua_pushnumber(state, color[0] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[1] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[2] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[3] as f64) };
|
||||
|
||||
4
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_viewport");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
@@ -390,9 +405,8 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
|
||||
ctx.layers().set_draw_color(last_segment.color);
|
||||
}
|
||||
|
||||
let layout = ctx.fonts().layout(job, ctx.window().scale_factor);
|
||||
ctx
|
||||
.layers()
|
||||
let layout = ctx.fonts().layout(job, ctx.window().scale_factor());
|
||||
ctx.layers()
|
||||
.draw_text(position, layout, is_absolute_position);
|
||||
|
||||
0
|
||||
@@ -415,9 +429,7 @@ 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 width = ctx
|
||||
.fonts()
|
||||
.get_text_width(job, ctx.window().scale_factor);
|
||||
let width = ctx.fonts().get_text_width(job, ctx.window().scale_factor());
|
||||
|
||||
unsafe { ffi::lua_pushnumber(state, width as f64) };
|
||||
1
|
||||
@@ -436,7 +448,7 @@ fn get_index_at_cur(
|
||||
let index = ctx.fonts().get_text_index_at_cursor(
|
||||
job,
|
||||
Point::new(cur_x, cur_y),
|
||||
ctx.window().scale_factor,
|
||||
ctx.window().scale_factor(),
|
||||
);
|
||||
|
||||
// convert to lua's 1-based indexing
|
||||
|
||||
+14
-6
@@ -18,7 +18,7 @@ pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
|
||||
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let scale_factor = ctx.window().scale_factor;
|
||||
let scale_factor = ctx.window().scale_factor();
|
||||
Ok(scale_factor)
|
||||
}
|
||||
|
||||
@@ -34,12 +34,20 @@ pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_dpi_scale_override(_: &Lua, _percent: i32) -> LuaResult<()> {
|
||||
// TODO:
|
||||
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
match percent {
|
||||
0 => ctx.window().scale_factor_override = None,
|
||||
p if p > 0 => ctx.window().scale_factor_override = Some(p as f32 / 100.0),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_dpi_scale_override(_: &Lua, _: ()) -> LuaResult<i32> {
|
||||
// TODO:
|
||||
Ok(0)
|
||||
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
match ctx.window().scale_factor_override {
|
||||
Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
|
||||
None => Ok(0),
|
||||
}
|
||||
}
|
||||
+94
-38
@@ -11,6 +11,7 @@ use crate::{
|
||||
window::WindowState,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use winit::{
|
||||
application::ApplicationHandler, event::*, event_loop::ActiveEventLoop, keyboard::PhysicalKey,
|
||||
@@ -19,6 +20,7 @@ use winit::{
|
||||
|
||||
struct FrameOutput {
|
||||
pub render_job: RenderJob,
|
||||
pub should_continue: bool,
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
@@ -26,36 +28,56 @@ pub struct AppState {
|
||||
pub input: InputState,
|
||||
pub fonts: Fonts,
|
||||
pub texture_manager: WrappedTextureManager,
|
||||
pub script_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
|
||||
self.input
|
||||
.set_mouse_pos(pos.to_logical(self.window.scale_factor));
|
||||
.set_mouse_pos(pos.to_logical(self.window.scale_factor()));
|
||||
}
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
gfx_context: Option<GraphicsContext>,
|
||||
state: AppState,
|
||||
game: Game,
|
||||
tessellator: Tessellator,
|
||||
needs_reconfigure: bool,
|
||||
force_render: bool,
|
||||
current_mode: AppMode,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new() -> Result<Self> {
|
||||
pub fn new(game: Game, custom_script_dir: Option<PathBuf>) -> Result<Self> {
|
||||
let uses_custom_script_dir = custom_script_dir.is_some();
|
||||
let script_dir = custom_script_dir.unwrap_or_else(|| game.script_dir());
|
||||
|
||||
let mut state = AppState {
|
||||
window: WindowState::default(),
|
||||
input: InputState::default(),
|
||||
fonts: Fonts::new(pob_font_definitions()),
|
||||
texture_manager: WrappedTextureManager::new(),
|
||||
script_dir,
|
||||
};
|
||||
|
||||
let current_mode = if uses_custom_script_dir {
|
||||
// Skip installer if custom script dir is provided.
|
||||
// Used for local testing
|
||||
let pob_mode = PoBMode::new(&mut state)?;
|
||||
AppMode::PoB(pob_mode)
|
||||
} else {
|
||||
AppMode::Install(InstallMode::new(game))
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
gfx_context: None,
|
||||
state: AppState {
|
||||
window: WindowState::default(),
|
||||
input: InputState::default(),
|
||||
fonts: Fonts::new(pob_font_definitions()),
|
||||
texture_manager: WrappedTextureManager::new(),
|
||||
},
|
||||
state,
|
||||
game,
|
||||
tessellator: Tessellator::default(),
|
||||
force_render: false,
|
||||
current_mode: AppMode::Install(InstallMode::new()),
|
||||
needs_reconfigure: true,
|
||||
force_render: true,
|
||||
current_mode,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -92,12 +114,10 @@ impl App {
|
||||
{
|
||||
RenderJob::Skip
|
||||
} else {
|
||||
self.force_render = false;
|
||||
|
||||
let meshes = self.tessellator.convert_clipped_primitives(
|
||||
mode_output.primitives,
|
||||
font_atlas_size,
|
||||
self.state.window.scale_factor,
|
||||
self.state.window.scale_factor(),
|
||||
);
|
||||
|
||||
RenderJob::Render {
|
||||
@@ -106,7 +126,10 @@ impl App {
|
||||
}
|
||||
};
|
||||
|
||||
Ok(FrameOutput { render_job })
|
||||
Ok(FrameOutput {
|
||||
render_job,
|
||||
should_continue: mode_output.should_continue,
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_event(&mut self, event: AppEvent) {
|
||||
@@ -116,7 +139,7 @@ impl App {
|
||||
}
|
||||
|
||||
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||
let (title, _app_id) = match Game::current() {
|
||||
let (title, _app_id) = match self.game {
|
||||
Game::Poe1 => ("Path of Building 1", "rusty-path-of-building-1"),
|
||||
Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"),
|
||||
};
|
||||
@@ -154,7 +177,6 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
if let Err(err) = self.create_window(event_loop) {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,26 +200,50 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
return;
|
||||
}
|
||||
|
||||
let render_job = match self.frame() {
|
||||
Ok(FrameOutput { render_job }) => render_job,
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
if self.needs_reconfigure {
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
let size = gfx.window.inner_size();
|
||||
gfx.resize(size.width, size.height);
|
||||
}
|
||||
};
|
||||
self.needs_reconfigure = false;
|
||||
// Render at least one frame after reconfigure
|
||||
self.force_render = true;
|
||||
}
|
||||
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
match gfx.render(render_job) {
|
||||
Ok(_) => {}
|
||||
// Reconfigure the surface if it's lost or outdated
|
||||
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
|
||||
let size = gfx.window.inner_size();
|
||||
gfx.resize(size.width, size.height);
|
||||
self.force_render = true;
|
||||
}
|
||||
let is_focused = self.state.window.is_focused;
|
||||
let is_hovered = self.state.window.is_hovered;
|
||||
let should_render = is_focused || is_hovered || self.force_render;
|
||||
|
||||
if should_render {
|
||||
let FrameOutput {
|
||||
render_job,
|
||||
should_continue,
|
||||
} = match self.frame() {
|
||||
Ok(frame_output) => frame_output,
|
||||
Err(err) => {
|
||||
log::error!("Unable to render: {err}");
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
match gfx.render(render_job, self.state.window.scale_factor()) {
|
||||
Ok(_) => {
|
||||
self.force_render = should_continue;
|
||||
|
||||
if is_focused || is_hovered || should_continue {
|
||||
self.state.window.request_redraw();
|
||||
}
|
||||
}
|
||||
// Reconfigure the surface if it's lost or outdated
|
||||
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
|
||||
self.needs_reconfigure = true;
|
||||
self.state.window.request_redraw();
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Unable to render: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,14 +251,17 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
profiling::finish_frame!();
|
||||
}
|
||||
WindowEvent::Resized(size) => {
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
gfx.resize(size.width, size.height);
|
||||
self.force_render = true;
|
||||
}
|
||||
self.state.window.size = PhysicalSize::new(size.width, size.height);
|
||||
self.needs_reconfigure = true;
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.state.window.is_focused = focused;
|
||||
if focused {
|
||||
self.state.window.request_redraw();
|
||||
}
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.state.window.scale_factor = scale_factor as f32;
|
||||
self.state.window.set_scale_factor(scale_factor as f32);
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
@@ -265,6 +314,13 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
|
||||
self.state.set_mouse_pos(pos);
|
||||
}
|
||||
WindowEvent::CursorEntered { .. } => {
|
||||
self.state.window.is_hovered = true;
|
||||
self.state.window.request_redraw();
|
||||
}
|
||||
WindowEvent::CursorLeft { .. } => {
|
||||
self.state.window.is_hovered = false;
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
let delta = match delta {
|
||||
MouseScrollDelta::LineDelta(_, y) => y,
|
||||
|
||||
+9
-20
@@ -9,10 +9,13 @@ pub struct Args {
|
||||
#[arg(value_enum)]
|
||||
pub game: Game,
|
||||
|
||||
pub build_path: Option<String>,
|
||||
#[arg(
|
||||
help = "URL of build to import on startup. Needs to use custom protocol schema, e.g. `pob://pobbin/<id>`"
|
||||
)]
|
||||
pub import_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, ValueEnum)]
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
pub enum Game {
|
||||
#[value(name = "poe1")]
|
||||
Poe1,
|
||||
@@ -20,30 +23,16 @@ pub enum Game {
|
||||
Poe2,
|
||||
}
|
||||
|
||||
static GAME_CONFIG: std::sync::OnceLock<Game> = std::sync::OnceLock::new();
|
||||
|
||||
impl Game {
|
||||
pub fn init(game: Game) {
|
||||
GAME_CONFIG.set(game).expect("Game should be uninitialized");
|
||||
}
|
||||
|
||||
pub fn current() -> &'static Game {
|
||||
GAME_CONFIG.get().expect("Game should be initialized")
|
||||
}
|
||||
|
||||
pub fn data_dir() -> PathBuf {
|
||||
let directory_name = match Self::current() {
|
||||
pub fn data_dir(&self) -> PathBuf {
|
||||
let directory_name = match self {
|
||||
Game::Poe1 => "RustyPathOfBuilding1",
|
||||
Game::Poe2 => "RustyPathOfBuilding2",
|
||||
};
|
||||
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")
|
||||
pub fn script_dir(&self) -> PathBuf {
|
||||
self.data_dir()
|
||||
}
|
||||
}
|
||||
@@ -67,8 +67,20 @@ impl From<Srgba> for image::Rgba<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Srgba> for [f32; 4] {
|
||||
fn from(value: Srgba) -> Self {
|
||||
value.0.map(u8_to_f32)
|
||||
}
|
||||
}
|
||||
|
||||
/// f32 [0.0, 1.0] -> u8 [0, 255]
|
||||
#[inline(always)]
|
||||
const fn f32_to_u8(c: f32) -> u8 {
|
||||
((c * 255.0) + 0.5) as u8
|
||||
}
|
||||
|
||||
/// u8 [0, 255] -> f32 [0.0, 1.0]
|
||||
#[inline(always)]
|
||||
const fn u8_to_f32(c: u8) -> f32 {
|
||||
c as f32 / 255.0
|
||||
}
|
||||
+8
-7
@@ -144,11 +144,13 @@ impl GraphicsContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&mut self, render_job: RenderJob) -> Result<(), wgpu::SurfaceError> {
|
||||
pub fn render(
|
||||
&mut self,
|
||||
render_job: RenderJob,
|
||||
scale_factor: f32,
|
||||
) -> Result<(), wgpu::SurfaceError> {
|
||||
profiling::scope!("render");
|
||||
|
||||
self.window.request_redraw();
|
||||
|
||||
if !self.is_surface_configured {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -174,7 +176,6 @@ impl GraphicsContext {
|
||||
} = render_job
|
||||
{
|
||||
let screen_size = PhysicalSize::new(self.config.width, self.config.height);
|
||||
let pixels_per_point = self.window.as_ref().scale_factor() as f32;
|
||||
|
||||
// upload new textures
|
||||
self.renderer
|
||||
@@ -186,7 +187,7 @@ impl GraphicsContext {
|
||||
&self.queue,
|
||||
&meshes,
|
||||
screen_size,
|
||||
pixels_per_point,
|
||||
scale_factor,
|
||||
);
|
||||
|
||||
let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
@@ -214,10 +215,10 @@ impl GraphicsContext {
|
||||
&mut rpass.forget_lifetime(),
|
||||
&meshes,
|
||||
screen_size,
|
||||
pixels_per_point,
|
||||
scale_factor,
|
||||
);
|
||||
|
||||
self.renderer.free_textures(&textures_delta)
|
||||
self.renderer.free_textures(&textures_delta);
|
||||
}
|
||||
|
||||
{
|
||||
|
||||
+248
-14
@@ -6,8 +6,8 @@ use crate::{
|
||||
fonts::{Alignment, FontStyle, LayoutJob},
|
||||
mode::{AppEvent, ModeFrameOutput, ModeTransition},
|
||||
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
|
||||
util::replace_in_matching_lines,
|
||||
};
|
||||
use anyhow::bail;
|
||||
use flate2::read::GzDecoder;
|
||||
use parley::{FontFamily, GenericFamily};
|
||||
use regex::Regex;
|
||||
@@ -49,12 +49,12 @@ pub struct InstallMode {
|
||||
}
|
||||
|
||||
impl InstallMode {
|
||||
pub fn new() -> Self {
|
||||
let script_dir = Game::script_dir();
|
||||
pub fn new(game: Game) -> Self {
|
||||
let script_dir = game.script_dir();
|
||||
let (progress_tx, progress_rx) = mpsc::channel();
|
||||
|
||||
thread::spawn(move || {
|
||||
if let Err(err) = install(script_dir.as_path(), &progress_tx) {
|
||||
if let Err(err) = install(script_dir.as_path(), game, &progress_tx) {
|
||||
progress_tx.send(Progress::Error(err)).unwrap();
|
||||
return;
|
||||
}
|
||||
@@ -73,6 +73,7 @@ impl InstallMode {
|
||||
Ok(ModeFrameOutput {
|
||||
primitives,
|
||||
can_elide: false,
|
||||
should_continue: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -137,7 +138,7 @@ impl InstallMode {
|
||||
};
|
||||
job.append(&progress_text, Srgba::WHITE);
|
||||
|
||||
let layout = app_state.fonts.layout(job, app_state.window.scale_factor);
|
||||
let layout = app_state.fonts.layout(job, app_state.window.scale_factor());
|
||||
|
||||
// center text vertically and horizontally
|
||||
let screen_size = app_state.window.logical_size().cast::<f32>();
|
||||
@@ -157,13 +158,14 @@ impl InstallMode {
|
||||
|
||||
fn install<P: AsRef<Path>>(
|
||||
target_dir: P,
|
||||
game: Game,
|
||||
progress_tx: &mpsc::Sender<Progress>,
|
||||
) -> anyhow::Result<()> {
|
||||
// Skip installation if version file exists
|
||||
let current_version = env!("CARGO_PKG_VERSION");
|
||||
let version_file_path = target_dir.as_ref().join("rpob.version");
|
||||
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}");
|
||||
@@ -173,7 +175,11 @@ fn install<P: AsRef<Path>>(
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
download_path_of_building(&target_dir, progress_tx)?;
|
||||
let compatibility_info = fetch_compatibility_info(game)?;
|
||||
let needed_pob_version = highest_supported_pob_version(&compatibility_info, current_version)
|
||||
.ok_or_else(|| anyhow::anyhow!("Unable to determine supported PoB version"))?;
|
||||
|
||||
download_path_of_building(&target_dir, game, needed_pob_version, progress_tx)?;
|
||||
replace_updatecheck(&target_dir)?;
|
||||
set_branch_and_platform(&target_dir)?;
|
||||
|
||||
@@ -183,20 +189,85 @@ fn install<P: AsRef<Path>>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Downloads latest release of Path of Building
|
||||
#[derive(Debug)]
|
||||
struct VersionReq {
|
||||
pob_ver: String,
|
||||
min_rpob_ver: String,
|
||||
}
|
||||
|
||||
/// Fetches and evaluates compatibility table
|
||||
fn fetch_compatibility_info(game: Game) -> anyhow::Result<Vec<VersionReq>> {
|
||||
let compatibility_info_file_name = match game {
|
||||
Game::Poe1 => "Compatibility_pob1.lua",
|
||||
Game::Poe2 => "Compatibility_pob2.lua",
|
||||
};
|
||||
|
||||
let compatibility_info_file_url = &format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
|
||||
compatibility_info_file_name
|
||||
);
|
||||
|
||||
let compatibility_info_file = download_file_contents(compatibility_info_file_url)?;
|
||||
|
||||
// Load and evaluate compatibility file contents as Lua code
|
||||
let lua = mlua::Lua::new();
|
||||
let compatibility_table = lua.load(compatibility_info_file).eval::<mlua::Table>()?;
|
||||
|
||||
// Compatibility table maps PoB version to minimum required Rusty PoB version
|
||||
Ok(compatibility_table
|
||||
.pairs::<String, String>()
|
||||
.filter_map(|p| p.ok())
|
||||
.map(|(pob_version, min_req_rpob_ver)| VersionReq {
|
||||
pob_ver: pob_version,
|
||||
min_rpob_ver: min_req_rpob_ver,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Determines highest PoB version supported by given Rusty PoB version
|
||||
fn highest_supported_pob_version<'a>(
|
||||
compatibility_info: &'a Vec<VersionReq>,
|
||||
rpob_version: &str,
|
||||
) -> Option<&'a str> {
|
||||
let mut highest_pob_version = None;
|
||||
for VersionReq {
|
||||
pob_ver,
|
||||
min_rpob_ver,
|
||||
} in compatibility_info
|
||||
{
|
||||
if is_higher_version(min_rpob_ver, rpob_version).unwrap_or(false) {
|
||||
// found PoB version that meets our minimum requirements
|
||||
match highest_pob_version {
|
||||
// make sure it is the highest PoB version possible
|
||||
Some(h_pob_version) => {
|
||||
if is_higher_version(h_pob_version, pob_ver).unwrap_or(false) {
|
||||
highest_pob_version = Some(pob_ver.as_str());
|
||||
}
|
||||
}
|
||||
None => highest_pob_version = Some(pob_ver.as_str()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
highest_pob_version
|
||||
}
|
||||
|
||||
/// Downloads specified version of Path of Building
|
||||
fn download_path_of_building<P: AsRef<Path>>(
|
||||
target_dir: P,
|
||||
game: Game,
|
||||
pob_version: &str,
|
||||
progress_tx: &mpsc::Sender<Progress>,
|
||||
) -> anyhow::Result<()> {
|
||||
log::info!("Downloading Path of Building assets...");
|
||||
|
||||
let repo = match Game::current() {
|
||||
let repo = match game {
|
||||
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
|
||||
Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2",
|
||||
};
|
||||
let url = format!(
|
||||
"https://github.com/{}/archive/refs/heads/master.tar.gz",
|
||||
repo
|
||||
"https://github.com/{}/archive/refs/tags/v{}.tar.gz",
|
||||
repo, pob_version
|
||||
);
|
||||
|
||||
let mut response = http_get_with_backoff(&url)?;
|
||||
@@ -267,9 +338,9 @@ fn download_path_of_building<P: AsRef<Path>>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replaces UpdateCheck with rusty-path-of-building's custom version of it.
|
||||
/// Replaces UpdateCheck with rusty-path-of-building's modified version
|
||||
fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
|
||||
log::info!("Downloading custom UpdateCheck.lua script...");
|
||||
log::info!("Downloading modified UpdateCheck.lua script...");
|
||||
|
||||
download_file(
|
||||
&format!(
|
||||
@@ -279,6 +350,31 @@ fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
|
||||
target_dir.as_ref().join("UpdateCheck.lua"),
|
||||
)?;
|
||||
|
||||
// Replace original checksum with checksum of modified update script
|
||||
let new_checksum = download_file_contents(&format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
|
||||
"UpdateCheck.lua.sha1"
|
||||
))?;
|
||||
|
||||
// file contains checksum followed by filename (separated by whitespace)
|
||||
// we only need the checksum
|
||||
let new_checksum = new_checksum
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid checksum file"))?;
|
||||
|
||||
let filename = target_dir.as_ref().join("manifest.xml");
|
||||
let manifest = fs::read_to_string(&filename)?;
|
||||
|
||||
let new_manifest = replace_in_matching_lines(
|
||||
&manifest,
|
||||
r#"name="UpdateCheck.lua""#,
|
||||
r#"sha1="([0-9A-Za-z]+)""#,
|
||||
&format!(r#"sha1="{}""#, new_checksum),
|
||||
);
|
||||
|
||||
fs::write(&filename, &new_manifest)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -302,6 +398,7 @@ fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Downloads file and saves it to given path
|
||||
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
|
||||
let mut response = http_get_with_backoff(url)?;
|
||||
|
||||
@@ -311,7 +408,19 @@ fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()>
|
||||
copy(&mut body.as_reader(), &mut file)?;
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("Unable to download: {}", url);
|
||||
anyhow::bail!("Unable to download: {}", url);
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads file and returns contents as string
|
||||
fn download_file_contents(url: &str) -> anyhow::Result<String> {
|
||||
let mut response = http_get_with_backoff(url)?;
|
||||
|
||||
if response.status().is_success() {
|
||||
let body = response.body_mut();
|
||||
Ok(body.read_to_string()?)
|
||||
} else {
|
||||
anyhow::bail!("Unable to download: {}", url);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,3 +541,128 @@ fn http_get_with_backoff(url: &str) -> anyhow::Result<Response<ureq::Body>> {
|
||||
return Ok(resp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares two SemVer versions and returns true if v2 is higher or equal than v1
|
||||
fn is_higher_version(v1: &str, v2: &str) -> anyhow::Result<bool> {
|
||||
let re = Regex::new(r"^(\d+)\.(\d+)\.(\d+)$").unwrap();
|
||||
|
||||
let parse_version = |v: &str| -> anyhow::Result<(u32, u32, u32)> {
|
||||
let caps = re
|
||||
.captures(v)
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid semver format: {}", v))?;
|
||||
|
||||
let major = caps[1].parse::<u32>().unwrap();
|
||||
let minor = caps[2].parse::<u32>().unwrap();
|
||||
let patch = caps[3].parse::<u32>().unwrap();
|
||||
|
||||
Ok((major, minor, patch))
|
||||
};
|
||||
|
||||
let (major1, minor1, patch1) = parse_version(v1)?;
|
||||
let (major2, minor2, patch2) = parse_version(v2)?;
|
||||
|
||||
Ok(major2 > major1
|
||||
|| (major2 == major1 && minor2 > minor1)
|
||||
|| (major2 == major1 && minor2 == minor1 && patch2 >= patch1))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_major_version() {
|
||||
assert_eq!(is_higher_version("1.0.0", "2.0.0").unwrap(), true);
|
||||
assert_eq!(is_higher_version("2.0.0", "1.0.0").unwrap(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_minor_version() {
|
||||
assert_eq!(is_higher_version("1.5.0", "1.6.0").unwrap(), true);
|
||||
assert_eq!(is_higher_version("1.10.0", "1.9.0").unwrap(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_patch_version() {
|
||||
assert_eq!(is_higher_version("1.0.3", "1.0.4").unwrap(), true);
|
||||
assert_eq!(is_higher_version("1.0.10", "1.0.9").unwrap(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_same_version() {
|
||||
assert_eq!(is_higher_version("1.5.3", "1.5.3").unwrap(), true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_semver_format() {
|
||||
assert!(is_higher_version("1.0", "2.0.0").is_err());
|
||||
assert!(is_higher_version("1.0.0", "2.0").is_err());
|
||||
assert!(is_higher_version("invalid", "2.0.0").is_err());
|
||||
assert!(is_higher_version("1.0.0", "a.bb.ccc").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_highest_supported_pob_ver() {
|
||||
let compat_info = vec![
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.56.0"),
|
||||
min_rpob_ver: String::from("0.1.0"),
|
||||
},
|
||||
// compat info might not be sorted by pob_version
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.58.0"),
|
||||
min_rpob_ver: String::from("0.2.6"),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.57.0"),
|
||||
min_rpob_ver: String::from("0.2.6"),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.58.1"),
|
||||
min_rpob_ver: String::from("0.2.8"),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.59.0"),
|
||||
min_rpob_ver: String::from("0.2.9"),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.59.1"),
|
||||
min_rpob_ver: String::from("0.2.10"),
|
||||
},
|
||||
VersionReq {
|
||||
pob_ver: String::from("2.59.2"),
|
||||
min_rpob_ver: String::from("0.2.10"),
|
||||
},
|
||||
];
|
||||
assert_eq!(highest_supported_pob_version(&compat_info, "0.0.2"), None);
|
||||
assert_eq!(highest_supported_pob_version(&compat_info, "a.b.c"), None);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.1.0"),
|
||||
Some("2.56.0")
|
||||
);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.2.0"),
|
||||
Some("2.56.0")
|
||||
);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.2.6"),
|
||||
Some("2.58.0")
|
||||
);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.2.7"),
|
||||
Some("2.58.0")
|
||||
);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.2.8"),
|
||||
Some("2.58.1")
|
||||
);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.2.9"),
|
||||
Some("2.59.0")
|
||||
);
|
||||
assert_eq!(
|
||||
highest_supported_pob_version(&compat_info, "0.2.10"),
|
||||
Some("2.59.2")
|
||||
);
|
||||
}
|
||||
}
|
||||
+46
-17
@@ -1,5 +1,4 @@
|
||||
use crate::{
|
||||
Game,
|
||||
api::{self, get_callback},
|
||||
app::AppState,
|
||||
args::Args,
|
||||
@@ -13,7 +12,7 @@ use crate::{
|
||||
window::WindowState,
|
||||
};
|
||||
use clap::Parser;
|
||||
use mlua::{Lua, Result as LuaResult, Table};
|
||||
use mlua::{Function, Lua, Result as LuaResult, Table, ThreadStatus};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
path::PathBuf,
|
||||
@@ -48,6 +47,7 @@ pub struct Context {
|
||||
input: Cell<*const InputState>,
|
||||
fonts: Cell<*mut Fonts>,
|
||||
texture_manager: Cell<*mut WrappedTextureManager>,
|
||||
script_dir: Cell<*const PathBuf>,
|
||||
current_working_dir: Cell<*mut PathBuf>,
|
||||
layers: Cell<*mut Layers>,
|
||||
needs_restart: Cell<*mut bool>,
|
||||
@@ -61,6 +61,7 @@ impl Context {
|
||||
input: Cell::new(std::ptr::null()),
|
||||
fonts: Cell::new(std::ptr::null_mut()),
|
||||
texture_manager: Cell::new(std::ptr::null_mut()),
|
||||
script_dir: Cell::new(std::ptr::null()),
|
||||
current_working_dir: Cell::new(std::ptr::null_mut()),
|
||||
layers: Cell::new(std::ptr::null_mut()),
|
||||
needs_restart: Cell::new(std::ptr::null_mut()),
|
||||
@@ -73,6 +74,7 @@ impl Context {
|
||||
self.input.set(&ctx.app.input);
|
||||
self.fonts.set(&mut ctx.app.fonts);
|
||||
self.texture_manager.set(&mut ctx.app.texture_manager);
|
||||
self.script_dir.set(&mut ctx.app.script_dir);
|
||||
self.current_working_dir
|
||||
.set(&mut ctx.pob.current_working_dir);
|
||||
self.layers.set(&mut ctx.pob.layers);
|
||||
@@ -85,6 +87,7 @@ impl Context {
|
||||
self.input.set(std::ptr::null());
|
||||
self.fonts.set(std::ptr::null_mut());
|
||||
self.texture_manager.set(std::ptr::null_mut());
|
||||
self.script_dir.set(std::ptr::null());
|
||||
self.current_working_dir.set(std::ptr::null_mut());
|
||||
self.layers.set(std::ptr::null_mut());
|
||||
self.needs_restart.set(std::ptr::null_mut());
|
||||
@@ -95,6 +98,7 @@ impl Context {
|
||||
ctx_accessor!(input: &InputState);
|
||||
ctx_accessor!(fonts: &mut Fonts);
|
||||
ctx_accessor!(texture_manager: &mut WrappedTextureManager);
|
||||
ctx_accessor!(script_dir: &PathBuf);
|
||||
ctx_accessor!(current_working_dir: &mut PathBuf);
|
||||
ctx_accessor!(layers: &mut Layers);
|
||||
ctx_accessor!(needs_restart: &mut bool);
|
||||
@@ -154,10 +158,10 @@ pub struct LuaInstance {
|
||||
}
|
||||
|
||||
impl LuaInstance {
|
||||
pub fn new() -> anyhow::Result<Self> {
|
||||
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new()));
|
||||
pub fn new(script_dir: &PathBuf) -> anyhow::Result<Self> {
|
||||
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new(script_dir.to_owned())));
|
||||
|
||||
let lua = Self::create_lua_state()?;
|
||||
let lua = Self::create_lua_state(script_dir)?;
|
||||
register_subscript_globals(&lua, &subscript_manager)?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -166,16 +170,16 @@ impl LuaInstance {
|
||||
})
|
||||
}
|
||||
|
||||
fn create_lua_state() -> LuaResult<Lua> {
|
||||
fn create_lua_state(script_dir: &PathBuf) -> LuaResult<Lua> {
|
||||
// SAFETY: use `unsafe_new` to allow loading of C modules
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
|
||||
// expose build arg to lua
|
||||
// expose import url to lua
|
||||
let args = Args::parse();
|
||||
let args_table = lua.create_sequence_from(std::iter::once(args.build_path))?;
|
||||
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
|
||||
lua.globals().set("arg", args_table)?;
|
||||
|
||||
Self::register_package_paths(&lua)?;
|
||||
Self::register_package_paths(&lua, script_dir)?;
|
||||
|
||||
// register context
|
||||
let ctx = Context::new();
|
||||
@@ -192,8 +196,8 @@ impl LuaInstance {
|
||||
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.set(pob_ctx);
|
||||
|
||||
let script_dir = Game::script_dir();
|
||||
change_working_directory(script_dir.as_path())?;
|
||||
let script_dir = pob_ctx.app.script_dir.as_path();
|
||||
change_working_directory(script_dir)?;
|
||||
self.load(script_dir.join("Launch.lua")).exec()?;
|
||||
|
||||
ctx.clear();
|
||||
@@ -201,33 +205,59 @@ impl LuaInstance {
|
||||
}
|
||||
|
||||
pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> {
|
||||
self.lua = Self::create_lua_state()?;
|
||||
self.lua = Self::create_lua_state(&ctx.app.script_dir)?;
|
||||
register_subscript_globals(&self.lua, &self.subscript_manager)?;
|
||||
self.launch(ctx)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run functions for subscripts and handle their completion/failure.
|
||||
pub fn handle_subscripts(&self, ctx: &mut PoBContext) {
|
||||
pub fn handle_subscripts(&self, pob_ctx: &mut PoBContext) {
|
||||
profiling::scope!("handle_subscripts");
|
||||
|
||||
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.set(pob_ctx);
|
||||
let subscript_events = self.subscript_manager.borrow_mut().process(self);
|
||||
ctx.clear();
|
||||
|
||||
// Handle finished/errored subscripts.
|
||||
for event in subscript_events {
|
||||
match event {
|
||||
SubscriptResult::SubscriptFinished { id, return_values } => {
|
||||
self.handle_event(PoBEvent::SubFinished { id, return_values }, ctx)
|
||||
self.handle_event(PoBEvent::SubFinished { id, return_values }, pob_ctx)
|
||||
.unwrap();
|
||||
}
|
||||
SubscriptResult::SubscriptError { id, error } => {
|
||||
self.handle_event(PoBEvent::SubError { id, error }, ctx)
|
||||
self.handle_event(PoBEvent::SubError { id, error }, pob_ctx)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_running_subscripts(&self) -> bool {
|
||||
self.subscript_manager.borrow().has_running_subscripts()
|
||||
}
|
||||
|
||||
pub fn has_active_coroutine(&self) -> bool {
|
||||
self.get_coroutines().is_ok_and(|coroutines| {
|
||||
coroutines.pairs::<mlua::Thread, bool>().any(|pair| {
|
||||
pair.is_ok_and(|(thread, _)| {
|
||||
matches!(
|
||||
thread.status(),
|
||||
ThreadStatus::Resumable | ThreadStatus::Running
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn get_coroutines(&self) -> LuaResult<Table> {
|
||||
let coroutine_module: Table = self.lua.globals().get("coroutine")?;
|
||||
let list_func: Function = coroutine_module.get("_list")?;
|
||||
list_func.call::<Table>(())
|
||||
}
|
||||
|
||||
pub fn handle_event(&self, event: PoBEvent, pob_ctx: &mut PoBContext) -> LuaResult<()> {
|
||||
profiling::scope!("handle_event", format!("{}", event));
|
||||
|
||||
@@ -260,8 +290,7 @@ impl LuaInstance {
|
||||
}
|
||||
|
||||
/// Adds "${script_dir}/lua" to package path
|
||||
pub fn register_package_paths(lua: &Lua) -> LuaResult<()> {
|
||||
let script_dir = Game::script_dir();
|
||||
pub fn register_package_paths(lua: &Lua, script_dir: &PathBuf) -> LuaResult<()> {
|
||||
let package: Table = lua.globals().get("package")?;
|
||||
let mut package_path: String = package.get("path")?;
|
||||
package_path.push(';');
|
||||
|
||||
+25
-6
@@ -1,8 +1,6 @@
|
||||
use crate::{
|
||||
app::App,
|
||||
args::{Args, Game},
|
||||
};
|
||||
use crate::{app::App, args::Args};
|
||||
use clap::Parser;
|
||||
use std::path::{Path, PathBuf};
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
mod api;
|
||||
@@ -40,12 +38,33 @@ fn main() -> anyhow::Result<()> {
|
||||
};
|
||||
|
||||
let args = Args::parse();
|
||||
Game::init(args.game);
|
||||
let script_dir = find_nearby_launch_script();
|
||||
|
||||
let mut app = App::new()?;
|
||||
let mut app = App::new(args.game, script_dir)?;
|
||||
|
||||
let event_loop = EventLoop::with_user_event().build()?;
|
||||
event_loop.run_app(&mut app)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Search for the Launch.lua file in nearby locations
|
||||
fn find_nearby_launch_script() -> Option<PathBuf> {
|
||||
let mut candidates = vec![Path::new("Launch.lua"), Path::new("src/Launch.lua")];
|
||||
|
||||
if let Ok(cwd) = std::env::current_dir()
|
||||
&& cwd.ends_with("runtime")
|
||||
{
|
||||
candidates.push(Path::new("../src/Launch.lua"));
|
||||
}
|
||||
|
||||
for candidate in candidates {
|
||||
if candidate.try_exists().is_ok_and(|exists| exists) {
|
||||
if let Some(Ok(candidate)) = candidate.parent().map(Path::canonicalize) {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
@@ -34,6 +34,9 @@ pub enum ModeTransition {
|
||||
pub struct ModeFrameOutput {
|
||||
pub primitives: Box<dyn Iterator<Item = ClippedPrimitive>>,
|
||||
pub can_elide: bool,
|
||||
/// Indicates that this should be redrawn again next frame even if user is not interacting with
|
||||
/// window
|
||||
pub should_continue: bool,
|
||||
}
|
||||
|
||||
pub enum AppMode {
|
||||
|
||||
+6
-1
@@ -34,7 +34,7 @@ impl PoBMode {
|
||||
is_dpi_aware: false,
|
||||
};
|
||||
|
||||
let lua_instance = LuaInstance::new()?;
|
||||
let lua_instance = LuaInstance::new(&app_state.script_dir)?;
|
||||
|
||||
let mut pob_ctx = PoBContext::new(app_state, &mut state);
|
||||
lua_instance.launch(&mut pob_ctx)?;
|
||||
@@ -68,9 +68,14 @@ impl PoBMode {
|
||||
let identical = layers_hash == self.previous_layers_hash;
|
||||
self.previous_layers_hash = layers_hash;
|
||||
|
||||
let has_active_subscript = self.lua_instance.has_running_subscripts();
|
||||
let has_active_coroutine = self.lua_instance.has_active_coroutine();
|
||||
let should_continue = has_active_subscript || has_active_coroutine;
|
||||
|
||||
Ok(ModeFrameOutput {
|
||||
primitives: self.state.layers.consume_layers(),
|
||||
can_elide: identical,
|
||||
should_continue,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+21
-13
@@ -1,14 +1,14 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
|
||||
use std::{collections::VecDeque, sync::mpsc::channel, thread::JoinHandle};
|
||||
|
||||
use crate::{api::get_callback, lua::LuaInstance};
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, Value};
|
||||
use mlua::{Integer, MultiValue, Number, Result as LuaResult};
|
||||
|
||||
use crate::api::get_callback;
|
||||
use crate::lua::LuaInstance;
|
||||
use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Result as LuaResult, Value};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
rc::Rc,
|
||||
sync::mpsc::{Receiver, Sender, TryRecvError, channel},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SubscriptResult {
|
||||
@@ -25,13 +25,15 @@ pub enum SubscriptResult {
|
||||
pub struct SubscriptManager {
|
||||
current_id: u64,
|
||||
scripts: Vec<Subscript>,
|
||||
script_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl SubscriptManager {
|
||||
pub fn new() -> Self {
|
||||
pub fn new(script_dir: PathBuf) -> Self {
|
||||
Self {
|
||||
current_id: 0,
|
||||
scripts: Vec::new(),
|
||||
script_dir,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +53,7 @@ impl SubscriptManager {
|
||||
blocking_calls,
|
||||
nonblocking_calls,
|
||||
arguments,
|
||||
self.script_dir.clone(),
|
||||
);
|
||||
self.scripts.push(subscript);
|
||||
id
|
||||
@@ -74,6 +77,10 @@ impl SubscriptManager {
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
pub fn has_running_subscripts(&self) -> bool {
|
||||
!self.scripts.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
enum SubscriptCall {
|
||||
@@ -115,6 +122,7 @@ impl Subscript {
|
||||
blocking_calls: Vec<String>,
|
||||
nonblocking_calls: Vec<String>,
|
||||
arguments: NativeMultiValue,
|
||||
script_dir: PathBuf,
|
||||
) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
|
||||
@@ -125,7 +133,7 @@ impl Subscript {
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
|
||||
// add ./lua to package.path and package.cpath
|
||||
LuaInstance::register_package_paths(&lua)?;
|
||||
LuaInstance::register_package_paths(&lua, &script_dir)?;
|
||||
|
||||
for function_name in blocking_calls {
|
||||
let thread_tx = tx.clone();
|
||||
@@ -305,7 +313,7 @@ pub fn register_subscript_globals(
|
||||
"IsSubScriptRunning",
|
||||
lua.create_function(is_subscript_running)?,
|
||||
)?;
|
||||
globals.set("IsSubScriptRunning", lua.create_function(abort_subscript)?)?;
|
||||
globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+25
@@ -27,3 +27,28 @@ pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
|
||||
t.hash(&mut state);
|
||||
state.finish()
|
||||
}
|
||||
|
||||
/// Performs replacement only in lines that match a given pattern
|
||||
pub fn replace_in_matching_lines(
|
||||
input: &str,
|
||||
match_pattern: &str,
|
||||
replace_pattern: &str,
|
||||
replacement_text: &str,
|
||||
) -> String {
|
||||
let match_re = regex::Regex::new(match_pattern).expect("Invalid match regex");
|
||||
let replace_re = regex::Regex::new(replace_pattern).expect("Invalid replace regex");
|
||||
|
||||
let mut output = String::new();
|
||||
for line in input.lines() {
|
||||
if match_re.is_match(line) {
|
||||
// if line matches the pattern, replace
|
||||
let replaced_line = replace_re.replace_all(line, replacement_text);
|
||||
output.push_str(&replaced_line);
|
||||
} else {
|
||||
// otherwise, keep original line
|
||||
output.push_str(line);
|
||||
}
|
||||
output.push('\n');
|
||||
}
|
||||
output
|
||||
}
|
||||
+22
-2
@@ -11,8 +11,11 @@ pub struct WindowState {
|
||||
clipboard: Option<Clipboard>,
|
||||
pub window: Option<Arc<Window>>,
|
||||
pub size: PhysicalSize<u32>,
|
||||
pub scale_factor: f32,
|
||||
scale_factor: f32,
|
||||
pub scale_factor_override: Option<f32>,
|
||||
pending_window_title: std::cell::Cell<Option<String>>,
|
||||
pub is_hovered: bool,
|
||||
pub is_focused: bool,
|
||||
}
|
||||
|
||||
impl Default for WindowState {
|
||||
@@ -21,8 +24,11 @@ impl Default for WindowState {
|
||||
window: None,
|
||||
size: Default::default(),
|
||||
scale_factor: 1.0,
|
||||
scale_factor_override: None,
|
||||
pending_window_title: std::cell::Cell::new(None),
|
||||
clipboard: None,
|
||||
is_hovered: true,
|
||||
is_focused: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,7 +57,15 @@ impl WindowState {
|
||||
}
|
||||
|
||||
pub fn logical_size(&self) -> LogicalSize<u32> {
|
||||
self.size.to_logical(self.scale_factor)
|
||||
self.size.to_logical(self.scale_factor())
|
||||
}
|
||||
|
||||
pub fn scale_factor(&self) -> f32 {
|
||||
self.scale_factor_override.unwrap_or(self.scale_factor)
|
||||
}
|
||||
|
||||
pub fn set_scale_factor(&mut self, scale_factor: f32) {
|
||||
self.scale_factor = scale_factor;
|
||||
}
|
||||
|
||||
pub fn focus(&self) {
|
||||
@@ -73,4 +87,10 @@ impl WindowState {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_redraw(&self) {
|
||||
if let Some(ref window) = self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user