Compare commits

...
7 Commits
Author SHA1 Message Date
meehl a858af2c38 chore: Release rusty-path-of-building version 0.2.10
Release / create-release (push) Successful in 4s
2025-12-15 23:20:27 +01:00
meehl 7fc3e340e7 Implement GetDrawColor 2025-12-15 17:56:52 +01:00
meehl dadf5c8804 Remove leftover dbg statement 2025-12-15 17:25:46 +01:00
meehl 031df6ed9c Store script directory in app context
This enables easier testing of the dev branch by providing a custom
script directory. Additionally, a Launch file is now searched for
in nearby locations and if found, used to determine a custom script
directory.
2025-12-15 17:18:56 +01:00
meehl e395e729e8 Add link to nixpkgs 2025-12-05 13:30:23 +01:00
meehl 76b5449bad installer: Write checksum of modified update script to manifest
This prevent having to perform a redundant update on first startup.
2025-12-05 13:03:11 +01:00
meehl f9f05aad08 Fix variable name 2025-12-03 23:09:03 +01:00
17 changed files with 221 additions and 89 deletions

No files matched your search

+12 -1
View File
@@ -2,6 +2,16 @@
## [Unreleased] - ReleaseDate ## [Unreleased] - ReleaseDate
## [0.2.10] - 2025-12-15
### Added
- Implement GetDrawColor
### Fixed
- Avoid redundant update after initial download
## [0.2.9] - 2025-12-03 ## [0.2.9] - 2025-12-03
### Added ### Added
@@ -133,8 +143,9 @@
- First release - First release
<!-- next-url --> <!-- next-url -->
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.9...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.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.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.7]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.6...v0.2.7
Generated
+1 -1
View File
@@ -2506,7 +2506,7 @@ checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]] [[package]]
name = "rusty-path-of-building" name = "rusty-path-of-building"
version = "0.2.9" version = "0.2.10"
dependencies = [ dependencies = [
"ahash", "ahash",
"anyhow", "anyhow",
+1 -1
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.9" version = "0.2.10"
edition = "2024" edition = "2024"
publish = false publish = false
+4
View File
@@ -22,6 +22,10 @@ Please check [the Arch Wiki](https://wiki.archlinux.org/title/Arch_User_Reposito
[![Stable version badge](https://img.shields.io/flathub/v/community.pathofbuilding.PathOfBuilding)](https://flathub.org/en/apps/community.pathofbuilding.PathOfBuilding) [![Stable version badge](https://img.shields.io/flathub/v/community.pathofbuilding.PathOfBuilding)](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 ### 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.
+7 -5
View File
@@ -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 mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::env; 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> { 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() { if module_path.extension().is_none() {
module_path.set_extension("lua"); module_path.set_extension("lua");
} }
let current_dir = env::current_dir()?; 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); let result = l.load(module_path).call::<MultiValue>(args);
change_working_directory(current_dir)?; change_working_directory(current_dir)?;
result result
} }
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> { 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() { if module_path.extension().is_none() {
module_path.set_extension("lua"); module_path.set_extension("lua");
} }
let current_dir = env::current_dir()?; 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) { let result = match l.load(module_path).call::<MultiValue>(args) {
// on success, callers expect a Nil followed by return values // on success, callers expect a Nil followed by return values
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()), Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
+6 -5
View File
@@ -2,18 +2,19 @@ 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,
lua::Context, lua::Context,
util::{change_working_directory, get_executable_dir}, util::{change_working_directory, get_executable_dir},
}; };
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<PathBuf> { pub fn get_user_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::user_data_dir()) let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(ctx.script_dir().join("userdata"))
} }
// parent directory of Launch.lua script // parent directory of Launch.lua script
pub fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> { pub fn get_script_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::script_dir()) let ctx = l.app_data_ref::<&'static Context>().unwrap();
Ok(ctx.script_dir().to_owned())
} }
// parent directory of executable // parent directory of executable
+15
View File
@@ -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 // thousands of times per frame. C functions are used to get raw access to
// the lua stack without the overhead. // the lua stack without the overhead.
unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? }; 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("SetViewport", lua.create_c_function(set_viewport)?)? };
unsafe { unsafe {
globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?; 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 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 { 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) };
+5 -5
View File
@@ -35,18 +35,18 @@ pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
} }
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> { pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static Context>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
match percent { match percent {
0 => socket.window().scale_factor_override = None, 0 => ctx.window().scale_factor_override = None,
p if p > 0 => socket.window().scale_factor_override = Some(p as f32 / 100.0), p if p > 0 => ctx.window().scale_factor_override = Some(p as f32 / 100.0),
_ => {} _ => {}
} }
Ok(()) Ok(())
} }
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> { pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
let socket = l.app_data_ref::<&'static Context>().unwrap(); let ctx = l.app_data_ref::<&'static Context>().unwrap();
match socket.window().scale_factor_override { match ctx.window().scale_factor_override {
Some(scale_factor) => Ok((scale_factor * 100.0) as i32), Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
None => Ok(0), None => Ok(0),
} }
+28 -9
View File
@@ -11,6 +11,7 @@ use crate::{
window::WindowState, window::WindowState,
}; };
use anyhow::Result; use anyhow::Result;
use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use winit::{ use winit::{
application::ApplicationHandler, event::*, event_loop::ActiveEventLoop, keyboard::PhysicalKey, application::ApplicationHandler, event::*, event_loop::ActiveEventLoop, keyboard::PhysicalKey,
@@ -27,6 +28,7 @@ pub struct AppState {
pub input: InputState, pub input: InputState,
pub fonts: Fonts, pub fonts: Fonts,
pub texture_manager: WrappedTextureManager, pub texture_manager: WrappedTextureManager,
pub script_dir: PathBuf,
} }
impl AppState { impl AppState {
@@ -39,6 +41,7 @@ impl AppState {
pub struct App { pub struct App {
gfx_context: Option<GraphicsContext>, gfx_context: Option<GraphicsContext>,
state: AppState, state: AppState,
game: Game,
tessellator: Tessellator, tessellator: Tessellator,
needs_reconfigure: bool, needs_reconfigure: bool,
force_render: bool, force_render: bool,
@@ -46,19 +49,35 @@ pub struct App {
} }
impl App { 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 { Ok(Self {
gfx_context: None, gfx_context: None,
state: AppState { state,
window: WindowState::default(), game,
input: InputState::default(),
fonts: Fonts::new(pob_font_definitions()),
texture_manager: WrappedTextureManager::new(),
},
tessellator: Tessellator::default(), tessellator: Tessellator::default(),
needs_reconfigure: true, needs_reconfigure: true,
force_render: true, force_render: true,
current_mode: AppMode::Install(InstallMode::new()), current_mode,
}) })
} }
@@ -120,7 +139,7 @@ impl App {
} }
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> { 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::Poe1 => ("Path of Building 1", "rusty-path-of-building-1"),
Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"), Game::Poe2 => ("Path of Building 2", "rusty-path-of-building-2"),
}; };
+5 -19
View File
@@ -15,7 +15,7 @@ pub struct Args {
pub import_url: Option<String>, pub import_url: Option<String>,
} }
#[derive(Debug, Clone, ValueEnum)] #[derive(Debug, Clone, Copy, ValueEnum)]
pub enum Game { pub enum Game {
#[value(name = "poe1")] #[value(name = "poe1")]
Poe1, Poe1,
@@ -23,30 +23,16 @@ pub enum Game {
Poe2, Poe2,
} }
static GAME_CONFIG: std::sync::OnceLock<Game> = std::sync::OnceLock::new();
impl Game { impl Game {
pub fn init(game: Game) { pub fn data_dir(&self) -> PathBuf {
GAME_CONFIG.set(game).expect("Game should be uninitialized"); let directory_name = match self {
}
pub fn current() -> &'static Game {
GAME_CONFIG.get().expect("Game should be initialized")
}
pub fn data_dir() -> PathBuf {
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 { pub fn script_dir(&self) -> PathBuf {
Game::data_dir() self.data_dir()
}
pub fn user_data_dir() -> PathBuf {
Game::data_dir().join("userdata")
} }
} }
+12
View File
@@ -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] /// f32 [0.0, 1.0] -> u8 [0, 255]
#[inline(always)] #[inline(always)]
const fn f32_to_u8(c: f32) -> u8 { const fn f32_to_u8(c: f32) -> u8 {
((c * 255.0) + 0.5) as 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
}
+38 -10
View File
@@ -6,6 +6,7 @@ use crate::{
fonts::{Alignment, FontStyle, LayoutJob}, fonts::{Alignment, FontStyle, LayoutJob},
mode::{AppEvent, ModeFrameOutput, ModeTransition}, mode::{AppEvent, ModeFrameOutput, ModeTransition},
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive}, renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
util::replace_in_matching_lines,
}; };
use flate2::read::GzDecoder; use flate2::read::GzDecoder;
use parley::{FontFamily, GenericFamily}; use parley::{FontFamily, GenericFamily};
@@ -48,12 +49,12 @@ pub struct InstallMode {
} }
impl InstallMode { impl InstallMode {
pub fn new() -> Self { pub fn new(game: Game) -> Self {
let script_dir = Game::script_dir(); let script_dir = game.script_dir();
let (progress_tx, progress_rx) = mpsc::channel(); let (progress_tx, progress_rx) = mpsc::channel();
thread::spawn(move || { 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(); progress_tx.send(Progress::Error(err)).unwrap();
return; return;
} }
@@ -157,6 +158,7 @@ impl InstallMode {
fn install<P: AsRef<Path>>( fn install<P: AsRef<Path>>(
target_dir: P, target_dir: P,
game: Game,
progress_tx: &mpsc::Sender<Progress>, progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
// Skip installation if version file exists // Skip installation if version file exists
@@ -173,11 +175,11 @@ fn install<P: AsRef<Path>>(
return Ok(()); return Ok(());
} }
let compatibility_info = fetch_compatibility_info()?; let compatibility_info = fetch_compatibility_info(game)?;
let needed_pob_version = highest_supported_pob_version(&compatibility_info, current_version) let needed_pob_version = highest_supported_pob_version(&compatibility_info, current_version)
.ok_or_else(|| anyhow::anyhow!("Unable to determine supported PoB version"))?; .ok_or_else(|| anyhow::anyhow!("Unable to determine supported PoB version"))?;
download_path_of_building(&target_dir, needed_pob_version, progress_tx)?; download_path_of_building(&target_dir, game, needed_pob_version, progress_tx)?;
replace_updatecheck(&target_dir)?; replace_updatecheck(&target_dir)?;
set_branch_and_platform(&target_dir)?; set_branch_and_platform(&target_dir)?;
@@ -194,8 +196,8 @@ struct VersionReq {
} }
/// Fetches and evaluates compatibility table /// Fetches and evaluates compatibility table
fn fetch_compatibility_info() -> anyhow::Result<Vec<VersionReq>> { fn fetch_compatibility_info(game: Game) -> anyhow::Result<Vec<VersionReq>> {
let compatibility_info_file_name = match Game::current() { let compatibility_info_file_name = match game {
Game::Poe1 => "Compatibility_pob1.lua", Game::Poe1 => "Compatibility_pob1.lua",
Game::Poe2 => "Compatibility_pob2.lua", Game::Poe2 => "Compatibility_pob2.lua",
}; };
@@ -253,12 +255,13 @@ fn highest_supported_pob_version<'a>(
/// Downloads specified version of Path of Building /// Downloads specified version of Path of Building
fn download_path_of_building<P: AsRef<Path>>( fn download_path_of_building<P: AsRef<Path>>(
target_dir: P, target_dir: P,
game: Game,
pob_version: &str, pob_version: &str,
progress_tx: &mpsc::Sender<Progress>, progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> { ) -> anyhow::Result<()> {
log::info!("Downloading Path of Building assets..."); log::info!("Downloading Path of Building assets...");
let repo = match Game::current() { let repo = match game {
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding", Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2", Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2",
}; };
@@ -335,9 +338,9 @@ fn download_path_of_building<P: AsRef<Path>>(
Ok(()) 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<()> { 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( download_file(
&format!( &format!(
@@ -347,6 +350,31 @@ fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
target_dir.as_ref().join("UpdateCheck.lua"), 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(()) Ok(())
} }
+20 -14
View File
@@ -1,5 +1,4 @@
use crate::{ use crate::{
Game,
api::{self, get_callback}, api::{self, get_callback},
app::AppState, app::AppState,
args::Args, args::Args,
@@ -48,6 +47,7 @@ pub struct Context {
input: Cell<*const InputState>, input: Cell<*const InputState>,
fonts: Cell<*mut Fonts>, fonts: Cell<*mut Fonts>,
texture_manager: Cell<*mut WrappedTextureManager>, texture_manager: Cell<*mut WrappedTextureManager>,
script_dir: Cell<*const PathBuf>,
current_working_dir: Cell<*mut PathBuf>, current_working_dir: Cell<*mut PathBuf>,
layers: Cell<*mut Layers>, layers: Cell<*mut Layers>,
needs_restart: Cell<*mut bool>, needs_restart: Cell<*mut bool>,
@@ -61,6 +61,7 @@ impl Context {
input: Cell::new(std::ptr::null()), input: Cell::new(std::ptr::null()),
fonts: Cell::new(std::ptr::null_mut()), fonts: Cell::new(std::ptr::null_mut()),
texture_manager: 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()), current_working_dir: Cell::new(std::ptr::null_mut()),
layers: Cell::new(std::ptr::null_mut()), layers: Cell::new(std::ptr::null_mut()),
needs_restart: 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.input.set(&ctx.app.input);
self.fonts.set(&mut ctx.app.fonts); self.fonts.set(&mut ctx.app.fonts);
self.texture_manager.set(&mut ctx.app.texture_manager); self.texture_manager.set(&mut ctx.app.texture_manager);
self.script_dir.set(&mut ctx.app.script_dir);
self.current_working_dir self.current_working_dir
.set(&mut ctx.pob.current_working_dir); .set(&mut ctx.pob.current_working_dir);
self.layers.set(&mut ctx.pob.layers); self.layers.set(&mut ctx.pob.layers);
@@ -85,6 +87,7 @@ impl Context {
self.input.set(std::ptr::null()); self.input.set(std::ptr::null());
self.fonts.set(std::ptr::null_mut()); self.fonts.set(std::ptr::null_mut());
self.texture_manager.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.current_working_dir.set(std::ptr::null_mut());
self.layers.set(std::ptr::null_mut()); self.layers.set(std::ptr::null_mut());
self.needs_restart.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!(input: &InputState);
ctx_accessor!(fonts: &mut Fonts); ctx_accessor!(fonts: &mut Fonts);
ctx_accessor!(texture_manager: &mut WrappedTextureManager); ctx_accessor!(texture_manager: &mut WrappedTextureManager);
ctx_accessor!(script_dir: &PathBuf);
ctx_accessor!(current_working_dir: &mut PathBuf); ctx_accessor!(current_working_dir: &mut PathBuf);
ctx_accessor!(layers: &mut Layers); ctx_accessor!(layers: &mut Layers);
ctx_accessor!(needs_restart: &mut bool); ctx_accessor!(needs_restart: &mut bool);
@@ -154,10 +158,10 @@ pub struct LuaInstance {
} }
impl LuaInstance { impl LuaInstance {
pub fn new() -> anyhow::Result<Self> { pub fn new(script_dir: &PathBuf) -> anyhow::Result<Self> {
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new())); 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)?; register_subscript_globals(&lua, &subscript_manager)?;
Ok(Self { Ok(Self {
@@ -166,7 +170,7 @@ 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 // SAFETY: use `unsafe_new` to allow loading of C modules
let lua = unsafe { Lua::unsafe_new() }; let lua = unsafe { Lua::unsafe_new() };
@@ -175,7 +179,7 @@ impl LuaInstance {
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?; let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
lua.globals().set("arg", args_table)?; lua.globals().set("arg", args_table)?;
Self::register_package_paths(&lua)?; Self::register_package_paths(&lua, script_dir)?;
// register context // register context
let ctx = Context::new(); let ctx = Context::new();
@@ -192,8 +196,8 @@ impl LuaInstance {
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap(); let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
ctx.set(pob_ctx); ctx.set(pob_ctx);
let script_dir = Game::script_dir(); let script_dir = pob_ctx.app.script_dir.as_path();
change_working_directory(script_dir.as_path())?; change_working_directory(script_dir)?;
self.load(script_dir.join("Launch.lua")).exec()?; self.load(script_dir.join("Launch.lua")).exec()?;
ctx.clear(); ctx.clear();
@@ -201,27 +205,30 @@ impl LuaInstance {
} }
pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> { 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)?; register_subscript_globals(&self.lua, &self.subscript_manager)?;
self.launch(ctx)?; self.launch(ctx)?;
Ok(()) Ok(())
} }
/// Run functions for subscripts and handle their completion/failure. /// 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"); 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); let subscript_events = self.subscript_manager.borrow_mut().process(self);
ctx.clear();
// Handle finished/errored subscripts. // Handle finished/errored subscripts.
for event in subscript_events { for event in subscript_events {
match event { match event {
SubscriptResult::SubscriptFinished { id, return_values } => { 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(); .unwrap();
} }
SubscriptResult::SubscriptError { id, error } => { SubscriptResult::SubscriptError { id, error } => {
self.handle_event(PoBEvent::SubError { id, error }, ctx) self.handle_event(PoBEvent::SubError { id, error }, pob_ctx)
.unwrap(); .unwrap();
} }
} }
@@ -283,8 +290,7 @@ impl LuaInstance {
} }
/// Adds "${script_dir}/lua" to package path /// Adds "${script_dir}/lua" to package path
pub fn register_package_paths(lua: &Lua) -> LuaResult<()> { pub fn register_package_paths(lua: &Lua, script_dir: &PathBuf) -> LuaResult<()> {
let script_dir = Game::script_dir();
let package: Table = lua.globals().get("package")?; let package: Table = lua.globals().get("package")?;
let mut package_path: String = package.get("path")?; let mut package_path: String = package.get("path")?;
package_path.push(';'); package_path.push(';');
+25 -6
View File
@@ -1,8 +1,6 @@
use crate::{ use crate::{app::App, args::Args};
app::App,
args::{Args, Game},
};
use clap::Parser; use clap::Parser;
use std::path::{Path, PathBuf};
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
mod api; mod api;
@@ -40,12 +38,33 @@ fn main() -> anyhow::Result<()> {
}; };
let args = Args::parse(); 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()?; let event_loop = EventLoop::with_user_event().build()?;
event_loop.run_app(&mut app)?; event_loop.run_app(&mut app)?;
Ok(()) 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
}
+1 -1
View File
@@ -34,7 +34,7 @@ impl PoBMode {
is_dpi_aware: false, 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); let mut pob_ctx = PoBContext::new(app_state, &mut state);
lua_instance.launch(&mut pob_ctx)?; lua_instance.launch(&mut pob_ctx)?;
+16 -12
View File
@@ -1,14 +1,14 @@
use std::cell::RefCell; use crate::{api::get_callback, lua::LuaInstance};
use std::rc::Rc;
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
use std::{collections::VecDeque, sync::mpsc::channel, thread::JoinHandle};
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use mlua::{Function, IntoLuaMulti, Lua, Value}; use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Result as LuaResult, Value};
use mlua::{Integer, MultiValue, Number, Result as LuaResult}; use std::{
cell::RefCell,
use crate::api::get_callback; collections::VecDeque,
use crate::lua::LuaInstance; path::PathBuf,
rc::Rc,
sync::mpsc::{Receiver, Sender, TryRecvError, channel},
thread::JoinHandle,
};
#[derive(Debug)] #[derive(Debug)]
pub enum SubscriptResult { pub enum SubscriptResult {
@@ -25,13 +25,15 @@ pub enum SubscriptResult {
pub struct SubscriptManager { pub struct SubscriptManager {
current_id: u64, current_id: u64,
scripts: Vec<Subscript>, scripts: Vec<Subscript>,
script_dir: PathBuf,
} }
impl SubscriptManager { impl SubscriptManager {
pub fn new() -> Self { pub fn new(script_dir: PathBuf) -> Self {
Self { Self {
current_id: 0, current_id: 0,
scripts: Vec::new(), scripts: Vec::new(),
script_dir,
} }
} }
@@ -51,6 +53,7 @@ impl SubscriptManager {
blocking_calls, blocking_calls,
nonblocking_calls, nonblocking_calls,
arguments, arguments,
self.script_dir.clone(),
); );
self.scripts.push(subscript); self.scripts.push(subscript);
id id
@@ -119,6 +122,7 @@ impl Subscript {
blocking_calls: Vec<String>, blocking_calls: Vec<String>,
nonblocking_calls: Vec<String>, nonblocking_calls: Vec<String>,
arguments: NativeMultiValue, arguments: NativeMultiValue,
script_dir: PathBuf,
) -> Self { ) -> Self {
let (tx, rx) = channel(); let (tx, rx) = channel();
@@ -129,7 +133,7 @@ impl Subscript {
let lua = unsafe { Lua::unsafe_new() }; let lua = unsafe { Lua::unsafe_new() };
// add ./lua to package.path and package.cpath // 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 { for function_name in blocking_calls {
let thread_tx = tx.clone(); let thread_tx = tx.clone();
+25
View File
@@ -27,3 +27,28 @@ pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
t.hash(&mut state); t.hash(&mut state);
state.finish() 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
}