Compare commits

...
10 Commits
Author SHA1 Message Date
meehl 9716157e3b chore: Release rusty-path-of-building version 0.2.1
Release / create-release (push) Successful in 4s
2025-10-28 23:28:03 +01:00
meehl 6e35123b5d Add stub for TakeScreenshot api function 2025-10-28 23:15:24 +01:00
meehl 38e3a39782 Implement missing SetForeground api function. Fixes #2 2025-10-28 23:12:09 +01:00
meehl f2387804c1 chore: Release rusty-path-of-building version 0.2.0
Release / create-release (push) Canceled after 0s
2025-10-28 17:35:57 +01:00
meehl 6b5b87cd8a Update dependencies 2025-10-28 17:32:19 +01:00
meehl 6a5135a6a6 Cleanup image loading 2025-10-28 17:18:07 +01:00
meehl 3352152ef6 Handle dpi awareness api feature flag 2025-10-28 16:54:44 +01:00
meehl 3ff483ad19 Notify windowing system right before presenting 2025-10-28 16:29:18 +01:00
meehl 3cdfbc823b Remove modified manifest and use new custom update checker 2025-10-27 23:31:03 +01:00
meehl d8e52218f8 Remove global context 2025-10-27 23:10:11 +01:00
28 changed files with 2065 additions and 1417 deletions

No files matched your search

+26 -1
View File
@@ -2,6 +2,29 @@
## [Unreleased] - ReleaseDate
## [0.2.1] - 2025-10-28
### Added
- Add stub for `TakeScreenshot` api function
### Fixed
- Fix crash caused by missing `SetForeground` api function
## [0.2.0] - 2025-10-28
### Added
- Add visual indicator for download progress in installer
- Handle dpi awareness feature flag
### Changed
- Remove global context
- Notify windowing system before presenting
- Cleanup image loading
## [0.1.2] - 2025-10-20
### Fixed
@@ -33,8 +56,10 @@
- First release
<!-- next-url -->
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.2...HEAD
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.1...HEAD
[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.1.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.1...v0.1.2
[0.1.1]: https://github.com/meehl/rusty-path-of-building/compare/v0.1.0...v0.1.1
[0.1.0]: https://github.com/meehl/rusty-path-of-building/releases/tag/v0.1.0
Generated
+297 -314
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -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.1.2"
version = "0.2.1"
edition = "2024"
publish = false
+81 -344
View File
@@ -1,219 +1,111 @@
use std::{
fs,
io::{Read, Write, stdout},
path::PathBuf,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::anyhow;
use directories::UserDirs;
use flate2::{
Compression,
read::{ZlibDecoder, ZlibEncoder},
};
use glob::glob;
use mlua::{
Function, IntoLua, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, String as LuaString,
Table, Value, Variadic,
};
pub use crate::api::callback::get_callback;
use crate::{
Game,
api::{image_handle::ImageHandle, rendering::PoBString, search_handle::SearchHandle},
context::CONTEXT,
input::{str_as_keycode, str_as_mousebutton},
util::{change_working_directory, get_executable_dir},
api::{
callback::{get_custom_callback, set_custom_callback, set_main_object},
clipboard::{copy, paste},
compression::{deflate, inflate},
console::{console_clear, console_execute, console_print_table, console_printf},
image_handle::new_image_handle,
input::{get_cursor_pos, is_key_down},
lua::{load_module, protected_call, protected_load_module},
paths::{
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, set_work_dir,
},
rendering::PoBString,
search_handle::new_search_handle,
window::{get_screen_scale, get_screen_size, set_foreground, set_window_title},
},
lua::ContextSocket,
};
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic};
use std::time::{SystemTime, UNIX_EPOCH};
mod callback;
mod clipboard;
mod compression;
mod console;
mod image_handle;
mod input;
mod lua;
mod paths;
mod rendering;
mod search_handle;
mod window;
/// Register functions that can be called from lua
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
let globals = lua.globals();
// callbacks
globals.set("SetMainObject", lua.create_function(set_main_object)?)?;
globals.set("SetCallback", lua.create_function(set_custom_callback)?)?;
globals.set("GetCallback", lua.create_function(get_custom_callback)?)?;
// paths
globals.set("GetUserPath", lua.create_function(get_user_path)?)?;
globals.set("GetScriptPath", lua.create_function(get_script_path)?)?;
globals.set("GetRuntimePath", lua.create_function(get_runtime_path)?)?;
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
globals.set("MakeDir", lua.create_function(make_dir)?)?;
// console
globals.set("ConPrintf", lua.create_function(console_printf)?)?;
globals.set("ConExecute", lua.create_function(console_execute)?)?;
globals.set("ConClear", lua.create_function(console_clear)?)?;
globals.set("ConPrintTable", lua.create_function(console_print_table)?)?;
globals.set("PCall", lua.create_function(protected_call)?)?;
// general
globals.set("GetTime", lua.create_function(get_time)?)?;
globals.set("MakeDir", lua.create_function(make_dir)?)?;
globals.set("StripEscapes", lua.create_function(strip_escapes)?)?;
globals.set("Inflate", lua.create_function(inflate)?)?;
globals.set("Deflate", lua.create_function(deflate)?)?;
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
globals.set("Copy", lua.create_function(copy)?)?;
globals.set("Paste", lua.create_function(paste)?)?;
globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?;
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?;
globals.set("IsKeyDown", lua.create_function(is_key_down)?)?;
globals.set("LoadModule", lua.create_function(load_module)?)?;
globals.set("PLoadModule", lua.create_function(protected_load_module)?)?;
globals.set("NewImageHandle", lua.create_function(new_image_handle)?)?;
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
globals.set("Restart", lua.create_function(restart)?)?;
globals.set("OpenURL", lua.create_function(open_url)?)?;
globals.set("RenderInit", lua.create_function(render_init)?)?;
let take_screenshot = |_: &Lua, ()| -> LuaResult<()> { Ok(()) }; // stub
globals.set("TakeScreenshot", lua.create_function(take_screenshot)?)?;
// compression
globals.set("Inflate", lua.create_function(inflate)?)?;
globals.set("Deflate", lua.create_function(deflate)?)?;
// search handle
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
// image handle
globals.set("NewImageHandle", lua.create_function(new_image_handle)?)?;
// clipboard
globals.set("Copy", lua.create_function(copy)?)?;
globals.set("Paste", lua.create_function(paste)?)?;
// input
globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?;
globals.set("IsKeyDown", lua.create_function(is_key_down)?)?;
// window
globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?;
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
globals.set("SetForeground", lua.create_function(set_foreground)?)?;
// lua
globals.set("PCall", lua.create_function(protected_call)?)?;
globals.set("LoadModule", lua.create_function(load_module)?)?;
globals.set("PLoadModule", lua.create_function(protected_load_module)?)?;
// NOTE: not used by PoB
let get_draw_layer = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let set_blend_mode = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let get_async_count = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let show_cursor = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let set_clear_color = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
globals.set("GetDrawLayer", lua.create_function(get_draw_layer)?)?;
globals.set("SetBlendMode", lua.create_function(set_blend_mode)?)?;
globals.set("GetAsyncCount", lua.create_function(get_async_count)?)?;
globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?;
globals.set("ShowCursor", lua.create_function(show_cursor)?)?;
globals.set("SetClearColor", lua.create_function(set_clear_color)?)?;
// rendering
rendering::register_globals(lua)?;
Ok(())
}
// During initialization, PoB calls `SetMainObject` with a callback table.
// Functions defined in this table are used to call back into Lua from Rust.
// Custom callback functions can be added with `SetCallback` and retrieved
// with `GetCallback`.
const CALLBACK_REGISTRY_NAME: &str = "uicallbacks";
pub fn get_callback(lua: &Lua, name: &str) -> LuaResult<Function> {
let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?;
let callback_function: Value = callback_table.get(name)?;
if callback_function.is_function() {
// function defined through `SetCallback`
return Ok(callback_function.as_function().unwrap().clone());
} else {
// look for function in `MainObject`
let main_object: Table = callback_table.get("MainObject")?;
let callback_function: Value = main_object.get(name)?;
if callback_function.is_function() {
// these functions expect `MainObject` as first argument so we bind it here
return callback_function.as_function().unwrap().bind(main_object);
}
}
Err(anyhow::anyhow!("Function '{}' not found", name).into())
}
fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> {
let callback_table = l.create_table()?;
callback_table.set("MainObject", main_object)?;
l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)?;
Ok(())
}
fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> {
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
callback_table.set(name, func)?;
Ok(())
}
fn get_custom_callback(l: &Lua, name: String) -> LuaResult<Function> {
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
let callback_function: Function = callback_table.get(name)?;
Ok(callback_function)
}
fn get_user_path(_: &Lua, _: ()) -> LuaResult<anyhow::Result<PathBuf>> {
let user_dirs = match UserDirs::new() {
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
fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::script_dir())
}
// parent directory of executable
fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
match get_executable_dir() {
Ok(exe_path) => Ok(exe_path),
Err(_) => Ok(PathBuf::new()),
}
}
fn console_printf(l: &Lua, (fmt, args): (String, MultiValue)) -> LuaResult<()> {
// uses lua's builtin string.format function
let string_module: Table = l.globals().get("string")?;
let format_func: Function = string_module.get("format")?;
let formatted_string = format_func.call::<String>((fmt, args))?;
println!("{formatted_string}");
Ok(())
}
fn console_execute(_l: &Lua, _cmd: String) -> LuaResult<()> {
Ok(())
}
fn console_clear(_l: &Lua, _: ()) -> LuaResult<()> {
Ok(())
}
fn print_table(table: &Table, indent: usize, recursive: bool) -> LuaResult<()> {
let mut lock = stdout().lock();
writeln!(lock, "{{")?;
for pair in table.pairs::<Value, Value>() {
let inner_ind = indent + 2;
let (key, value) = pair?;
if key.is_string() {
write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?,)?;
} else {
write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?,)?;
}
if value.is_table() {
if recursive {
print_table(value.as_table().unwrap(), indent + 2, recursive)?;
} else {
writeln!(lock, "{}", value.to_string()?)?;
}
} else if value.is_string() {
writeln!(lock, "\"{}\"", value.to_string()?)?;
} else {
writeln!(lock, "{}", value.to_string()?)?;
}
}
writeln!(lock, "{0:>1$}}}", "", indent)?;
Ok(())
}
fn console_print_table(_l: &Lua, (table, no_recursive): (Table, Option<bool>)) -> LuaResult<()> {
print_table(&table, 0, !no_recursive.unwrap_or(true))?;
Ok(())
}
fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult<MultiValue> {
match func.call::<MultiValue>(args) {
// callers expect first return value to be Nil on success
Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()),
// otherwise it is set to error message.
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
}
}
fn get_time(_l: &Lua, _: ()) -> LuaResult<u128> {
Ok(SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -221,174 +113,13 @@ fn get_time(_l: &Lua, _: ()) -> LuaResult<u128> {
.as_millis())
}
fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
match fs::create_dir_all(path) {
// callers expect first return value to be true on success
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
// otherwise it is set to Nil and second return value is set to error msg
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
}
}
fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
Ok(PoBString(&text).strip_escapes())
}
fn inflate(l: &Lua, compressed: LuaString) -> LuaResult<MultiValue> {
let compressed_bytes = &compressed.as_bytes()[..];
// prevent decompression of input larger than 128MiB
if compressed_bytes.len() > (128 << 20) {
return Ok((Value::Nil, "Input larger than 128 MiB")
.into_lua_multi(l)
.unwrap());
}
let mut decoder = ZlibDecoder::new(compressed_bytes);
let mut decompressed = Vec::new();
match decoder.read_to_end(&mut decompressed) {
Ok(_) => Ok(l
.create_string(&decompressed)
.unwrap()
.into_lua_multi(l)
.unwrap()),
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
}
}
fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult<MultiValue> {
let uncompressed_bytes = &uncompressed.as_bytes()[..];
// prevent compression of input larger than 128MiB
if uncompressed_bytes.len() > (128 << 20) {
return Ok((Value::Nil, "Input larger than 128 MiB")
.into_lua_multi(l)
.unwrap());
}
let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast());
let mut compressed = Vec::new();
match encoder.read_to_end(&mut compressed) {
Ok(_) => Ok(l
.create_string(&compressed)
.unwrap()
.into_lua_multi(l)
.unwrap()),
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
}
}
fn new_search_handle(
l: &Lua,
(pattern, find_directories): (String, Option<bool>),
) -> LuaResult<Value> {
if let Ok(paths) = glob(&pattern) {
let directories_only = find_directories.is_some_and(|x| x);
let mut handle = SearchHandle::new(paths, directories_only);
// try to get the first result
handle.next();
// only return a handle if at least one file/directory is found
if handle.current.is_some() {
return handle.into_lua(l);
}
};
Ok(Value::Nil)
}
fn get_work_dir(_: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(CONTEXT.with_borrow(|ctx| ctx.current_working_dir().to_path_buf()))
}
// NOTE: unused
fn set_work_dir(_: &Lua, path: String) -> LuaResult<()> {
CONTEXT.with_borrow_mut(|ctx| ctx.set_current_working_dir(path.into()));
Ok(())
}
fn copy(_: &Lua, text: String) -> LuaResult<()> {
CONTEXT.with_borrow_mut(|ctx| {
ctx.clipboard
.set_text(text)
.map_err(|e| anyhow::anyhow!("{}", e))
})?;
Ok(())
}
fn paste(_: &Lua, _: ()) -> LuaResult<String> {
let text = CONTEXT.with_borrow_mut(|ctx| {
ctx.clipboard
.get_text()
.map_err(|e| anyhow::anyhow!("{}", e))
})?;
Ok(text)
}
// NOTE: needs to return physical size if this MR gets merged:
// https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2/pull/1420
fn get_screen_size(_: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let size = CONTEXT.with_borrow(|ctx| ctx.screen_size_logical());
Ok((size.width, size.height))
}
fn get_screen_scale(_: &Lua, _: ()) -> LuaResult<f32> {
Ok(CONTEXT.with_borrow(|ctx| ctx.pixels_per_point() as f32))
}
fn get_cursor_pos(_: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let pos = CONTEXT.with_borrow(|ctx| ctx.mouse_pos_logical());
Ok((pos.x as u32, pos.y as u32))
}
fn is_key_down(_: &Lua, key_name: String) -> LuaResult<bool> {
if let Some(code) = str_as_keycode(&key_name) {
Ok(CONTEXT.with_borrow(|ctx| ctx.input_state.key_pressed(code)))
} else if let Some(button) = str_as_mousebutton(&key_name) {
Ok(CONTEXT.with_borrow(|ctx| ctx.input_state.mouse_pressed(button)))
} else {
Ok(false)
}
}
fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::script_dir().join(name);
if module_path.extension().is_none() {
module_path.set_extension("lua");
}
change_working_directory(Game::script_dir().as_path())?;
let result = l.load(module_path).call::<MultiValue>(args);
CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?;
result
}
fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::script_dir().join(name);
if module_path.extension().is_none() {
module_path.set_extension("lua");
}
change_working_directory(Game::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()),
// otherwise it is set to error message.
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
};
CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?;
result
}
fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
Ok(ImageHandle::Unloaded)
}
fn set_window_title(_: &Lua, title: String) -> LuaResult<()> {
CONTEXT.with_borrow(|ctx| ctx.set_window_title(&title));
Ok(())
}
fn restart(_: &Lua, _: ()) -> LuaResult<()> {
CONTEXT.with_borrow_mut(|ctx| ctx.needs_restart = true);
fn restart(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
*socket.needs_restart() = true;
Ok(())
}
@@ -399,6 +130,12 @@ fn open_url(l: &Lua, url: String) -> LuaResult<MultiValue> {
}
}
fn render_init(_: &Lua, _features: Variadic<String>) -> LuaResult<()> {
fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
for feature in features {
if feature == "DPI_AWARE" {
*socket.is_dpi_aware() = true;
}
}
Ok(())
}
+44
View File
@@ -0,0 +1,44 @@
use mlua::{Function, Lua, Result as LuaResult, Table, Value};
// During initialization, PoB calls `SetMainObject` with a callback table.
// Functions defined in this table are used to call back into Lua from Rust.
// Custom callback functions can be added with `SetCallback` and retrieved
// with `GetCallback`.
const CALLBACK_REGISTRY_NAME: &str = "uicallbacks";
pub fn get_callback(lua: &Lua, name: &str) -> LuaResult<Function> {
let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?;
let callback_function: Value = callback_table.get(name)?;
if callback_function.is_function() {
// function defined through `SetCallback`
return Ok(callback_function.as_function().unwrap().clone());
} else {
// look for function in `MainObject`
let main_object: Table = callback_table.get("MainObject")?;
let callback_function: Value = main_object.get(name)?;
if callback_function.is_function() {
// these functions expect `MainObject` as first argument so we bind it here
return callback_function.as_function().unwrap().bind(main_object);
}
}
Err(anyhow::anyhow!("Function '{}' not found", name).into())
}
pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> {
let callback_table = l.create_table()?;
callback_table.set("MainObject", main_object)?;
l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)?;
Ok(())
}
pub fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> {
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
callback_table.set(name, func)?;
Ok(())
}
pub fn get_custom_callback(l: &Lua, name: String) -> LuaResult<Function> {
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
let callback_function: Function = callback_table.get(name)?;
Ok(callback_function)
}
+20
View File
@@ -0,0 +1,20 @@
use crate::lua::ContextSocket;
use mlua::{Lua, Result as LuaResult};
pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
socket
.clipboard()
.set_text(text)
.map_err(|e| anyhow::anyhow!("{}", e))?;
Ok(())
}
pub fn paste(l: &Lua, _: ()) -> LuaResult<String> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let text = socket
.clipboard()
.get_text()
.map_err(|e| anyhow::anyhow!("{}", e))?;
Ok(text)
}
+50
View File
@@ -0,0 +1,50 @@
use flate2::{
Compression,
read::{ZlibDecoder, ZlibEncoder},
};
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, String as LuaString, Value};
use std::io::Read;
pub fn inflate(l: &Lua, compressed: LuaString) -> LuaResult<MultiValue> {
let compressed_bytes = &compressed.as_bytes()[..];
// prevent decompression of input larger than 128MiB
if compressed_bytes.len() > (128 << 20) {
return Ok((Value::Nil, "Input larger than 128 MiB")
.into_lua_multi(l)
.unwrap());
}
let mut decoder = ZlibDecoder::new(compressed_bytes);
let mut decompressed = Vec::new();
match decoder.read_to_end(&mut decompressed) {
Ok(_) => Ok(l
.create_string(&decompressed)
.unwrap()
.into_lua_multi(l)
.unwrap()),
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
}
}
pub fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult<MultiValue> {
let uncompressed_bytes = &uncompressed.as_bytes()[..];
// prevent compression of input larger than 128MiB
if uncompressed_bytes.len() > (128 << 20) {
return Ok((Value::Nil, "Input larger than 128 MiB")
.into_lua_multi(l)
.unwrap());
}
let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast());
let mut compressed = Vec::new();
match encoder.read_to_end(&mut compressed) {
Ok(_) => Ok(l
.create_string(&compressed)
.unwrap()
.into_lua_multi(l)
.unwrap()),
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
}
}
+56
View File
@@ -0,0 +1,56 @@
use mlua::{Function, Lua, MultiValue, Result as LuaResult, Table, Value};
use std::io::{Write, stdout};
pub fn console_printf(l: &Lua, (fmt, args): (String, MultiValue)) -> LuaResult<()> {
// uses lua's builtin string.format function
let string_module: Table = l.globals().get("string")?;
let format_func: Function = string_module.get("format")?;
let formatted_string = format_func.call::<String>((fmt, args))?;
println!("{formatted_string}");
Ok(())
}
pub fn console_execute(_l: &Lua, _cmd: String) -> LuaResult<()> {
Ok(())
}
pub fn console_clear(_l: &Lua, _: ()) -> LuaResult<()> {
Ok(())
}
pub fn console_print_table(
_l: &Lua,
(table, no_recursive): (Table, Option<bool>),
) -> LuaResult<()> {
print_table(&table, 0, !no_recursive.unwrap_or(true))?;
Ok(())
}
fn print_table(table: &Table, indent: usize, recursive: bool) -> LuaResult<()> {
let mut lock = stdout().lock();
writeln!(lock, "{{")?;
for pair in table.pairs::<Value, Value>() {
let inner_ind = indent + 2;
let (key, value) = pair?;
if key.is_string() {
write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?,)?;
} else {
write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?,)?;
}
if value.is_table() {
if recursive {
print_table(value.as_table().unwrap(), indent + 2, recursive)?;
} else {
writeln!(lock, "{}", value.to_string()?)?;
}
} else if value.is_string() {
writeln!(lock, "\"{}\"", value.to_string()?)?;
} else {
writeln!(lock, "{}", value.to_string()?)?;
}
}
writeln!(lock, "{0:>1$}}}", "", indent)?;
Ok(())
}
+52 -49
View File
@@ -1,9 +1,12 @@
use mlua::{MultiValue, UserData};
use crate::{
context::CONTEXT,
lua::ContextSocket,
renderer::textures::{TextureHandle, TextureOptions},
};
use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
pub fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
Ok(ImageHandle::Unloaded)
}
#[derive(Clone)]
pub enum ImageHandle {
@@ -13,52 +16,7 @@ pub enum ImageHandle {
impl UserData for ImageHandle {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_method_mut(
"Load",
|_, this, (image_path, flags): (String, MultiValue)| {
let mut is_async = false;
let mut options = TextureOptions::LINEAR_REPEAT;
for flag in flags.iter() {
if let Some(flag) = flag.as_string() {
match flag.to_string_lossy().as_str() {
"CLAMP" => options.wrap_mode = wgpu::AddressMode::ClampToEdge,
"NEAREST" => options.magnification = wgpu::FilterMode::Nearest,
"ASYNC" => is_async = true,
"MIPMAP" => options.generate_mipmaps = true,
_ => {}
}
}
}
match this {
// replace image data if already allocated
ImageHandle::Loaded(texture_handle) => {
CONTEXT.with_borrow(|ctx| {
// in case of error, stay loaded with current texture
let _ = ctx.texture_manager.update_texture(
texture_handle.id(),
image_path,
options,
is_async,
);
});
}
// create new texture handle
ImageHandle::Unloaded => {
CONTEXT.with_borrow(|ctx| {
if let Ok(handle) = ctx
.texture_manager
.load_texture(image_path, options, is_async)
{
*this = ImageHandle::Loaded(handle);
}
});
}
}
Ok(())
},
);
methods.add_method_mut("Load", load);
methods.add_method_mut("Unload", |_, this, ()| {
match this {
@@ -92,3 +50,48 @@ impl UserData for ImageHandle {
});
}
}
fn load(
lua: &Lua,
handle: &mut ImageHandle,
(image_path, flags): (String, MultiValue),
) -> LuaResult<()> {
let socket = lua.app_data_ref::<&'static ContextSocket>().unwrap();
let mut is_async = false;
let mut options = TextureOptions::LINEAR_REPEAT;
for flag in flags.iter() {
if let Some(flag) = flag.as_string() {
match flag.to_string_lossy().as_str() {
"CLAMP" => options.wrap_mode = wgpu::AddressMode::ClampToEdge,
"NEAREST" => options.magnification = wgpu::FilterMode::Nearest,
"ASYNC" => is_async = true,
"MIPMAP" => options.generate_mipmaps = true,
_ => {}
}
}
}
match handle {
// replace image data if already allocated
ImageHandle::Loaded(texture_handle) => {
// in case of error, stay loaded with current texture
let _ = socket.texture_manager().update_texture(
texture_handle.id(),
image_path,
options,
is_async,
);
}
// create new texture handle
ImageHandle::Unloaded => {
if let Ok(tex_handle) = socket
.texture_manager()
.load_texture(image_path, options, is_async)
{
*handle = ImageHandle::Loaded(tex_handle);
}
}
}
Ok(())
}
+23
View File
@@ -0,0 +1,23 @@
use crate::{
input::{str_as_keycode, str_as_mousebutton},
lua::ContextSocket,
};
use mlua::{Lua, Result as LuaResult};
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let pos = socket.input().mouse_pos();
Ok((pos.x as u32, pos.y as u32))
}
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
if let Some(code) = str_as_keycode(&key_name) {
Ok(socket.input().key_pressed(code))
} else if let Some(button) = str_as_mousebutton(&key_name) {
Ok(socket.input().mouse_pressed(button))
} else {
Ok(false)
}
}
+43
View File
@@ -0,0 +1,43 @@
use crate::{args::Game, util::change_working_directory};
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::env;
pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult<MultiValue> {
match func.call::<MultiValue>(args) {
// callers expect first return value to be Nil on success
Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()),
// otherwise it is set to error message.
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
}
}
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::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())?;
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);
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())?;
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()),
// otherwise it is set to error message.
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
};
change_working_directory(current_dir)?;
result
}
+60
View File
@@ -0,0 +1,60 @@
use anyhow::anyhow;
use directories::UserDirs;
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::{fs, path::PathBuf};
use crate::{
args::Game,
lua::ContextSocket,
util::{change_working_directory, get_executable_dir},
};
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<anyhow::Result<PathBuf>> {
let user_dirs = match UserDirs::new() {
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
pub fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::script_dir())
}
// parent directory of executable
pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
match get_executable_dir() {
Ok(exe_path) => Ok(exe_path),
Err(_) => Ok(PathBuf::new()),
}
}
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
Ok(socket.current_working_dir().to_path_buf())
}
// NOTE: unused
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
if change_working_directory(&path).is_ok() {
*socket.current_working_dir() = path.into();
}
Ok(())
}
pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
match fs::create_dir_all(path) {
// callers expect first return value to be true on success
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
// otherwise it is set to Nil and second return value is set to error msg
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
}
}
+97 -49
View File
@@ -1,9 +1,9 @@
use crate::{
api::image_handle::ImageHandle,
color::Srgba,
context::CONTEXT,
dpi::Uv,
fonts::{Alignment, LayoutJob},
lua::ContextSocket,
math::{Point, Quad, Rect, Size},
};
use core::ffi::{c_int, c_void};
@@ -16,6 +16,17 @@ use std::sync::LazyLock;
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
let globals = lua.globals();
// unused functions
let get_draw_layer = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let set_blend_mode = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let get_async_count = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
let set_clear_color = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
globals.set("GetDrawLayer", lua.create_function(get_draw_layer)?)?;
globals.set("SetBlendMode", lua.create_function(set_blend_mode)?)?;
globals.set("GetAsyncCount", lua.create_function(get_async_count)?)?;
globals.set("SetClearColor", lua.create_function(set_clear_color)?)?;
// rendering functions
// NOTE: unfortunately, mlua's conversion of function arguments adds a lot of
// overhead. this is very noticeable for the draw functions which can be called
@@ -114,6 +125,10 @@ 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 {
//profiling::scope!("set_draw_color");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
match nargs {
@@ -121,7 +136,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
1 => {
let esc_str = str_from_stack!(state, -nargs);
let color = Srgba::from_escape_code(esc_str);
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
socket.layers().set_draw_color(color);
}
// rgb
3 => {
@@ -129,7 +144,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 b = f32_from_stack!(state, -nargs + 2);
let color = Srgba::new_f32(r, g, b, 1.0);
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
socket.layers().set_draw_color(color);
}
// rgba
4 => {
@@ -138,7 +153,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 a = f32_from_stack!(state, -nargs + 3);
let color = Srgba::new_f32(r, g, b, a);
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
socket.layers().set_draw_color(color);
}
_ => panic!("Unexpected number of arguments"),
};
@@ -148,17 +163,23 @@ 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 {
//profiling::scope!("set_viewport");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
match nargs {
0 => CONTEXT.with_borrow_mut(|ctx| ctx.reset_viewport()),
0 => socket
.layers()
.set_viewport_from_size(socket.window().logical_size()),
4 => {
let x = f32_from_stack!(state, -nargs);
let y = f32_from_stack!(state, -nargs + 1);
let w = f32_from_stack!(state, -nargs + 2);
let h = f32_from_stack!(state, -nargs + 3);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
CONTEXT.with_borrow_mut(|ctx| ctx.set_viewport(rect));
socket.layers().set_viewport(rect);
}
_ => panic!("Unexpected number of arguments"),
};
@@ -168,13 +189,17 @@ 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 {
//profiling::scope!("set_draw_layer");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
match nargs {
1 => {
let layer = i32_from_stack!(state, -nargs);
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, 0));
socket.layers().set_draw_layer(layer, 0);
}
2 => {
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
@@ -187,9 +212,9 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
};
let sublayer = i32_from_stack!(state, -nargs + 1);
if let Some(layer) = layer {
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, sublayer));
socket.layers().set_draw_layer(layer, sublayer);
} else {
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_sublayer(sublayer));
socket.layers().set_draw_sublayer(sublayer);
}
}
_ => panic!("Unexpected number of arguments"),
@@ -200,6 +225,10 @@ 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 {
//profiling::scope!("draw_image");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
@@ -239,13 +268,17 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
0
};
CONTEXT.with_borrow_mut(|ctx| ctx.draw_rect(texture_id, rect, uv, layer_idx));
socket.layers().draw_rect(texture_id, rect, uv, layer_idx);
0
}
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image_quad", format!("args: {:?}", args));
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
@@ -303,13 +336,17 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
0
};
CONTEXT.with_borrow_mut(|ctx| ctx.draw_quad(texture_id, quad, uv, layer_idx));
socket.layers().draw_quad(texture_id, quad, uv, layer_idx);
0
}
unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_string");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
@@ -331,48 +368,53 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
let mut position = Point::new(x, y);
let mut is_absolute_position = false;
CONTEXT.with_borrow_mut(|ctx| {
// the position needs to be adjusted for some alignments to match PoBs behavior
let screen_size = ctx.screen_size_logical();
let halign = match alignment {
PoBTextAlignment::Left => Alignment::Min,
PoBTextAlignment::Center => {
position.x += screen_size.width as f32 / 2.0;
is_absolute_position = true;
Alignment::Center
}
PoBTextAlignment::Right => {
position.x = screen_size.width as f32 - position.x;
is_absolute_position = true;
Alignment::Max
}
PoBTextAlignment::CenterX => Alignment::Center,
PoBTextAlignment::RightX => Alignment::Max,
};
let current_draw_color = ctx.get_draw_color();
let job = build_layout_job(
text,
current_draw_color,
font_type,
line_height,
Some(halign),
);
// NOTE: color escape codes modify the current draw color.
// set current draw color to color of last segment to match PoB's behavior
if let Some(last_segment) = job.segments.last() {
ctx.set_draw_color(last_segment.color);
// the position needs to be adjusted for some alignments to match PoBs behavior
let screen_size = socket.window().logical_size();
let halign = match alignment {
PoBTextAlignment::Left => Alignment::Min,
PoBTextAlignment::Center => {
position.x += screen_size.width as f32 / 2.0;
is_absolute_position = true;
Alignment::Center
}
PoBTextAlignment::Right => {
position.x = screen_size.width as f32 - position.x;
is_absolute_position = true;
Alignment::Max
}
PoBTextAlignment::CenterX => Alignment::Center,
PoBTextAlignment::RightX => Alignment::Max,
};
ctx.draw_text(position, job, is_absolute_position);
});
let current_draw_color = socket.layers().get_draw_color();
let job = build_layout_job(
text,
current_draw_color,
font_type,
line_height,
Some(halign),
);
// NOTE: color escape codes modify the current draw color.
// set current draw color to color of last segment to match PoB's behavior
if let Some(last_segment) = job.segments.last() {
socket.layers().set_draw_color(last_segment.color);
}
let layout = socket.fonts().layout(job, socket.window().scale_factor);
socket
.layers()
.draw_text(position, layout, is_absolute_position);
0
}
unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("get_string_width");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
@@ -386,23 +428,29 @@ 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 = CONTEXT.with_borrow_mut(|ctx| ctx.get_text_width(job));
let width = socket
.fonts()
.get_text_width(job, socket.window().scale_factor);
unsafe { ffi::lua_pushnumber(state, width as f64) };
1
}
fn get_index_at_cur(
_: &Lua,
l: &Lua,
(line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32),
) -> LuaResult<usize> {
//profiling::scope!("get_char_index_at_cur");
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let font_type = font_type.parse::<PoBFontType>()?;
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
let index =
CONTEXT.with_borrow_mut(|ctx| ctx.get_text_index_at_cursor(job, Point::new(cur_x, cur_y)));
let index = socket.fonts().get_text_index_at_cursor(
job,
Point::new(cur_x, cur_y),
socket.window().scale_factor,
);
// convert to lua's 1-based indexing
Ok(index + 1)
+23 -5
View File
@@ -1,9 +1,27 @@
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use glob::{Paths, glob};
use mlua::{IntoLua, Lua, Result as LuaResult, UserData, Value};
use std::{
fs,
path::{Path, PathBuf},
time::SystemTime,
};
use glob::Paths;
use mlua::{IntoLua, UserData};
pub fn new_search_handle(
l: &Lua,
(pattern, find_directories): (String, Option<bool>),
) -> LuaResult<Value> {
if let Ok(paths) = glob(&pattern) {
let directories_only = find_directories.is_some_and(|x| x);
let mut handle = SearchHandle::new(paths, directories_only);
// try to get the first result
handle.next();
// only return a handle if at least one file/directory is found
if handle.current.is_some() {
return handle.into_lua(l);
}
};
Ok(Value::Nil)
}
pub struct SearchHandle {
paths: Paths,
+34
View File
@@ -0,0 +1,34 @@
use crate::{
dpi::{LogicalSize, PhysicalSize},
lua::ContextSocket,
};
use mlua::{Lua, Result as LuaResult};
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let size = if *socket.is_dpi_aware() {
let PhysicalSize { width, height, .. } = socket.window().size;
(width, height)
} else {
let LogicalSize { width, height, .. } = socket.window().logical_size();
(width, height)
};
Ok(size)
}
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
Ok(socket.window().scale_factor)
}
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
socket.window().set_window_title(&title);
Ok(())
}
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
socket.window().focus();
Ok(())
}
+176 -85
View File
@@ -1,56 +1,123 @@
use std::sync::Arc;
use crate::{
dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize},
fonts::Fonts,
gfx::{GraphicsContext, RenderJob},
input::InputState,
installer::InstallMode,
mode::{AppEvent, AppMode, ModeTransition},
pob::PoBMode,
renderer::{tessellator::Tessellator, textures::WrappedTextureManager},
window::WindowState,
};
use anyhow::Result;
use arboard::Clipboard;
use std::sync::Arc;
use winit::{
application::ApplicationHandler,
dpi::PhysicalPosition,
event::*,
event_loop::ActiveEventLoop,
keyboard::{ModifiersState, PhysicalKey},
window::Window,
};
use crate::{
context::{CONTEXT, FrameOutput},
gfx::GraphicsContext,
input::{keycode_as_str, mousebutton_as_str},
lua::LuaInstance,
};
struct FrameOutput {
pub render_job: RenderJob,
}
pub struct AppState {
pub window: WindowState,
pub input: InputState,
pub fonts: Fonts,
pub texture_manager: WrappedTextureManager,
pub clipboard: Clipboard,
}
impl AppState {
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
self.input
.set_mouse_pos(pos.to_logical(self.window.scale_factor));
}
}
pub struct App {
gfx_context: Option<GraphicsContext>,
lua_instance: LuaInstance,
state: AppState,
tessellator: Tessellator,
force_render: bool,
current_mode: AppMode,
}
impl App {
pub fn new() -> Result<Self> {
let lua_instance = LuaInstance::new()?;
Ok(Self {
gfx_context: None,
lua_instance,
state: AppState {
window: WindowState::default(),
input: InputState::default(),
fonts: Fonts::new(),
texture_manager: WrappedTextureManager::new(),
clipboard: arboard::Clipboard::new()?,
},
tessellator: Tessellator::default(),
force_render: false,
current_mode: AppMode::Install(InstallMode::new()),
})
}
fn frame(&mut self) -> FrameOutput {
// Handle restart requests
if CONTEXT.with_borrow(|ctx| ctx.needs_restart) {
match self.lua_instance.restart() {
Ok(_) => CONTEXT.with_borrow_mut(|ctx| ctx.needs_restart = false),
Err(e) => panic!("Error occused while restarting lua instance: {}", e),
fn update(&mut self) -> anyhow::Result<()> {
let transition = self.current_mode.update(&mut self.state)?;
if let Some(transition) = transition {
self.current_mode = match transition {
ModeTransition::PoB => {
let pob_mode = PoBMode::new(&mut self.state)?;
AppMode::PoB(pob_mode)
}
};
}
Ok(())
}
fn frame(&mut self) -> anyhow::Result<FrameOutput> {
self.state.fonts.begin_frame();
let mode_output = self.current_mode.frame(&mut self.state)?;
let font_atlas_size = self.state.fonts.font_atlas().size();
if let Some(font_image_delta) = self.state.fonts.font_atlas_delta() {
self.state
.texture_manager
.update_font_texture(font_image_delta);
}
let textures_delta = self.state.texture_manager.take_delta();
let render_job = if mode_output.can_elide && textures_delta.is_empty() && !self.force_render
{
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,
);
RenderJob::Render {
meshes,
textures_delta,
}
};
self.lua_instance.handle_subscripts();
Ok(FrameOutput { render_job })
}
// Clear data from previous frame and prepare for new one
CONTEXT.with_borrow_mut(|ctx| ctx.begin_frame());
// Call back into lua and tell it to draw a frame
self.lua_instance.on_frame().unwrap();
// End frame and get outupts
CONTEXT.with_borrow_mut(|ctx| ctx.end_frame())
fn handle_event(&mut self, event: AppEvent) {
if let Err(err) = self.current_mode.handle_event(&mut self.state, event) {
log::error!("{err}");
}
}
}
@@ -65,7 +132,7 @@ impl ApplicationHandler<GraphicsContext> for App {
}
};
CONTEXT.with_borrow_mut(|ctx| ctx.set_window(Arc::clone(&window)));
self.state.window.set_window(Arc::clone(&window));
self.gfx_context = match pollster::block_on(GraphicsContext::new(window)) {
Ok(gfx) => Some(gfx),
@@ -83,23 +150,28 @@ impl ApplicationHandler<GraphicsContext> for App {
_window_id: winit::window::WindowId,
event: WindowEvent,
) {
CONTEXT.with_borrow_mut(|ctx| ctx.on_window_event(&event));
match event {
WindowEvent::CloseRequested => {
self.lua_instance.on_exit().unwrap();
event_loop.exit()
}
WindowEvent::Resized(size) => {
if let Some(ref mut gfx) = self.gfx_context {
gfx.resize(size.width, size.height);
CONTEXT.with_borrow_mut(|ctx| ctx.force_render = true)
}
self.handle_event(AppEvent::Exit);
event_loop.exit();
}
WindowEvent::RedrawRequested => {
profiling::scope!("RedrawRequested");
let FrameOutput { render_job } = self.frame();
if let Err(err) = self.update() {
log::error!("{err}");
event_loop.exit();
return;
}
let render_job = match self.frame() {
Ok(FrameOutput { render_job }) => render_job,
Err(err) => {
log::error!("{err}");
event_loop.exit();
return;
}
};
if let Some(ref mut gfx) = self.gfx_context {
match gfx.render(render_job) {
@@ -108,7 +180,7 @@ impl ApplicationHandler<GraphicsContext> for App {
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
let size = gfx.window.inner_size();
gfx.resize(size.width, size.height);
CONTEXT.with_borrow_mut(|ctx| ctx.force_render = true)
self.force_render = true;
}
Err(err) => {
log::error!("Unable to render: {err}");
@@ -118,69 +190,88 @@ 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);
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
self.state.window.scale_factor = scale_factor as f32;
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
logical_key,
state,
text,
..
},
..
} => {
// Only call OnChar if no modifier key except SHIFT is pressed.
// This prevents 'v' from getting inserted into a text field
// when 'CTRL + v' is used to paste.
if state.is_pressed()
&& CONTEXT.with_borrow(|ctx| {
ctx.input_state
.modifiers()
.difference(ModifiersState::SHIFT)
.is_empty()
})
&& let Some(text) = text
{
self.lua_instance.on_char(&text).unwrap();
}
self.state.input.set_key_pressed(code, state.is_pressed());
if let Some(key_string) = keycode_as_str(code) {
match state {
ElementState::Pressed => {
self.lua_instance.on_key_down(&key_string, false).unwrap();
let event = match state {
ElementState::Pressed => AppEvent::KeyDown { code },
ElementState::Released => AppEvent::KeyUp { code },
};
self.handle_event(event);
// handle text input
if state.is_pressed() {
match logical_key {
winit::keyboard::Key::Character(text) => {
// only emit event if no modifier except Shift is pressed.
let modifiers = self.state.input.key_modifiers;
if modifiers.difference(ModifiersState::SHIFT).is_empty() {
for ch in text.chars() {
let event = AppEvent::CharacterInput { ch };
self.handle_event(event);
}
}
}
ElementState::Released => {
self.lua_instance.on_key_up(&key_string).unwrap();
winit::keyboard::Key::Named(named) => {
if named == winit::keyboard::NamedKey::Space {
let event = AppEvent::CharacterInput { ch: ' ' };
self.handle_event(event);
}
}
_ => {}
}
}
}
WindowEvent::ModifiersChanged(modifiers) => {
self.state.input.key_modifiers = modifiers.state();
}
WindowEvent::MouseInput { state, button, .. } => {
if let Some(button_string) = mousebutton_as_str(button) {
match state {
ElementState::Pressed => {
let is_double_click = CONTEXT
.with_borrow_mut(|ctx| ctx.input_state.is_double_click(button));
self.lua_instance
.on_key_down(&button_string, is_double_click)
.unwrap();
}
ElementState::Released => {
self.lua_instance.on_key_up(&button_string).unwrap();
}
}
}
let is_double_click = self
.state
.input
.set_mouse_pressed(button, state.is_pressed());
let event = match state {
ElementState::Pressed => AppEvent::MouseDown {
button,
is_double_click,
},
ElementState::Released => AppEvent::MouseUp { button },
};
self.handle_event(event);
}
WindowEvent::CursorMoved { position, .. } => {
let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
self.state.set_mouse_pos(pos);
}
WindowEvent::MouseWheel { delta, .. } => {
let vertical_scroll_amount = match delta {
MouseScrollDelta::LineDelta(_, y) => y as f64,
MouseScrollDelta::PixelDelta(PhysicalPosition { y, .. }) => y,
let delta = match delta {
MouseScrollDelta::LineDelta(_, y) => y,
MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition { y, .. }) => {
y as f32
}
};
if vertical_scroll_amount > 0.0 {
self.lua_instance.on_key_up("WHEELUP").unwrap();
} else if vertical_scroll_amount < 0.0 {
self.lua_instance.on_key_up("WHEELDOWN").unwrap();
}
let event = AppEvent::MouseWheel { delta };
self.handle_event(event);
}
_ => {}
}
-251
View File
@@ -1,251 +0,0 @@
use crate::{
Game,
color::Srgba,
dpi::{
ConvertToLogical, LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad,
NormalizedRect, PhysicalRect, PhysicalSize,
},
fonts::{Fonts, LayoutJob},
input::InputState,
layers::Layers,
renderer::{
mesh::ClippedMesh,
primitives::{QuadPrimitive, QuadTexture, RectPrimitive, RectTexture, TextPrimitive},
tessellator::Tessellator,
textures::{TextureId, TexturesDelta, WrappedTextureManager},
},
util::{calculate_hash, change_working_directory},
};
use arboard::Clipboard;
use std::{
cell::RefCell,
path::{Path, PathBuf},
sync::Arc,
};
use winit::{event::WindowEvent, window::Window};
// NOTE: This looks ugly but i haven't found a better way to do it yet.
// The C functions used for rendering need a way to access the context.
// They can't be defined as closures like all other lua callback functions
// and we can't change their arguments. The only way for them to access
// something outside their scope is to have some kind of static variable.
thread_local! {
pub static CONTEXT: RefCell<Context> = RefCell::new(Context::new());
}
pub struct Context {
window: Option<Arc<Window>>,
screen_size: PhysicalSize<u32>,
pixels_per_point: f32,
pub input_state: InputState,
pub clipboard: Clipboard,
pub texture_manager: WrappedTextureManager,
tessellator: Tessellator,
fonts: Fonts,
layers: Layers,
current_draw_color: Srgba,
previous_layers_hash: u64,
current_working_dir: PathBuf,
pub needs_restart: bool,
pub force_render: bool,
}
impl Context {
pub fn new() -> Self {
Self {
window: None,
screen_size: PhysicalSize::new(0, 0),
pixels_per_point: 1.0,
input_state: InputState::default(),
clipboard: Clipboard::new().unwrap(),
texture_manager: WrappedTextureManager::new(),
tessellator: Tessellator::default(),
fonts: Fonts::new(),
layers: Layers::new(),
current_draw_color: Srgba::WHITE,
previous_layers_hash: 0,
current_working_dir: Game::script_dir().clone(),
needs_restart: false,
force_render: false,
}
}
pub fn begin_frame(&mut self) {
profiling::scope!("begin_frame");
self.fonts.begin_frame();
self.layers.reset();
self.reset_viewport();
}
pub fn end_frame(&mut self) -> FrameOutput {
profiling::scope!("end_frame");
let font_atlas_size = self.fonts.font_atlas().size();
if let Some(font_image_delta) = self.fonts.font_atlas_delta() {
self.texture_manager.update_font_texture(font_image_delta);
}
let textures_delta = self.texture_manager.take_delta();
// Skip rendering this frame if identical to last one and no textures changed
let layers_hash = calculate_hash(&self.layers);
let elide_frame = layers_hash == self.previous_layers_hash && textures_delta.is_empty();
let render_job = if elide_frame && !self.force_render {
RenderJob::Skip
} else {
self.force_render = false;
self.previous_layers_hash = layers_hash;
let primitives = self.layers.consume_layers();
let meshes = self.tessellator.convert_clipped_primitives(
primitives,
font_atlas_size,
self.pixels_per_point,
);
RenderJob::Render {
meshes,
textures_delta,
}
};
FrameOutput { render_job }
}
pub fn on_window_event(&mut self, event: &WindowEvent) {
match event {
WindowEvent::Resized(size) => {
self.screen_size = PhysicalSize::new(size.width, size.height);
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
self.pixels_per_point = *scale_factor as f32;
}
_ => {}
}
self.input_state.on_window_event(event);
}
pub fn screen_size_logical(&self) -> LogicalSize<u32> {
self.screen_size.to_logical(self.pixels_per_point)
}
pub fn mouse_pos_logical(&self) -> LogicalPoint<f32> {
self.input_state
.mouse_pos()
.to_logical(self.pixels_per_point)
}
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
pub fn current_working_dir(&self) -> &Path {
&self.current_working_dir
}
pub fn set_current_working_dir(&mut self, path: PathBuf) {
if change_working_directory(&path).is_ok() {
self.current_working_dir = path;
}
}
pub fn set_window(&mut self, window: Arc<Window>) {
self.window = Some(window);
}
pub fn set_window_title(&self, title: &str) {
if let Some(ref window) = self.window {
window.set_title(title);
}
}
}
pub enum RenderJob {
Render {
meshes: Vec<ClippedMesh>,
textures_delta: TexturesDelta,
},
Skip,
}
pub struct FrameOutput {
pub render_job: RenderJob,
}
impl Context {
pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) {
self.layers.set_draw_layer(layer, sublayer);
}
pub fn set_draw_sublayer(&mut self, sublayer: i32) {
self.layers.set_draw_sublayer(sublayer);
}
pub fn set_viewport(&mut self, viewport: LogicalRect<f32>) {
self.layers.set_viewport(viewport);
}
pub fn reset_viewport(&mut self) {
let viewport = PhysicalRect::from_size(self.screen_size);
self.layers
.set_viewport(viewport.to_logical(self.pixels_per_point));
}
pub fn set_draw_color(&mut self, color: Srgba) {
self.current_draw_color = color;
}
pub fn get_draw_color(&self) -> Srgba {
self.current_draw_color
}
pub fn draw_rect(
&mut self,
texture_id: Option<TextureId>,
rect: LogicalRect<f32>,
uv: NormalizedRect,
layer_idx: u32,
) {
let texture = texture_id.map(|id| RectTexture::new(id, uv, layer_idx));
let primitive = RectPrimitive::new(rect, self.current_draw_color, texture);
self.layers.add_rect(primitive);
}
pub fn draw_quad(
&mut self,
texture_id: Option<TextureId>,
quad: LogicalQuad<f32>,
uv: NormalizedQuad,
layer_idx: u32,
) {
let texture = texture_id.map(|id| QuadTexture::new(id, uv, layer_idx));
let primitive = QuadPrimitive::new(quad, self.current_draw_color, texture);
self.layers.add_quad(primitive);
}
pub fn draw_text(
&mut self,
position: LogicalPoint<f32>,
job: LayoutJob,
is_absolute_position: bool,
) {
let layout = self.fonts.layout(job, self.pixels_per_point as f32);
let primitive = TextPrimitive::new(position, layout);
self.layers.add_text(primitive, is_absolute_position);
}
/// Width of laid out text
pub fn get_text_width(&mut self, job: LayoutJob) -> i32 {
let layout = self.fonts.layout(job, self.pixels_per_point as f32);
layout.width() as i32
}
/// Text index based on where cursor is positioned within text
pub fn get_text_index_at_cursor(&mut self, job: LayoutJob, cursor: LogicalPoint<f32>) -> usize {
let layout = self.fonts.layout(job, self.pixels_per_point as f32);
layout.cursor_index(cursor)
}
}
+18 -1
View File
@@ -1,6 +1,6 @@
use crate::{
color::Srgba,
dpi::LogicalVector,
dpi::{LogicalPoint, LogicalVector},
fonts::{
atlas::FontAtlas, glyph_key::SubpixelBin, layout::LayoutRow, rasterizer::GlyphRasterizer,
},
@@ -287,6 +287,23 @@ impl Fonts {
self.glyph_rasterizer.clear();
self.layout_cache.clear();
}
/// Width of laid out text
pub fn get_text_width(&mut self, job: LayoutJob, pixels_per_point: f32) -> i32 {
let layout = self.layout(job, pixels_per_point);
layout.width() as i32
}
/// Text index at cursor location
pub fn get_text_index_at_cursor(
&mut self,
job: LayoutJob,
cursor: LogicalPoint<f32>,
pixels_per_point: f32,
) -> usize {
let layout = self.layout(job, pixels_per_point);
layout.cursor_index(cursor)
}
}
struct CachedLayout {
+14 -1
View File
@@ -1,8 +1,19 @@
use crate::{context::RenderJob, dpi::PhysicalSize, renderer::Renderer};
use crate::{
dpi::PhysicalSize,
renderer::{Renderer, mesh::ClippedMesh, textures::TexturesDelta},
};
use std::sync::Arc;
use wgpu::{Texture, TextureFormat, TextureView};
use winit::window::Window;
pub enum RenderJob {
Render {
meshes: Vec<ClippedMesh>,
textures_delta: TexturesDelta,
},
Skip,
}
pub struct GraphicsContext {
surface: wgpu::Surface<'static>,
device: wgpu::Device,
@@ -220,6 +231,8 @@ impl GraphicsContext {
}
self.queue.submit(std::iter::once(encoder.finish()));
self.window.pre_present_notify();
output.present();
if suboptimal {
+127 -153
View File
@@ -1,72 +1,40 @@
use crate::dpi::PhysicalPoint;
use crate::dpi::LogicalPoint;
use ahash::{HashMap, HashSet};
use std::time::{Duration, Instant};
use winit::{
event::{KeyEvent, MouseButton, WindowEvent},
keyboard::{KeyCode, ModifiersState, PhysicalKey},
event::MouseButton,
keyboard::{KeyCode, ModifiersState},
};
#[derive(Default)]
pub struct InputState {
key_modifiers: ModifiersState,
pub key_modifiers: ModifiersState,
keys_pressed: HashSet<KeyCode>,
mouse_pressed: HashSet<MouseButton>,
mouse_last_pressed: HashMap<MouseButton, Instant>,
cursor_pos: PhysicalPoint<f32>,
cursor_pos: LogicalPoint<f32>,
}
impl InputState {
pub fn set_key_pressed(&mut self, code: KeyCode, is_pressed: bool) {
if is_pressed {
self.keys_pressed.insert(code);
} else {
self.keys_pressed.remove(&code);
}
}
pub fn key_pressed(&self, code: KeyCode) -> bool {
self.keys_pressed.contains(&code)
}
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
self.mouse_pressed.contains(&button)
}
pub fn mouse_pos(&self) -> PhysicalPoint<f32> {
self.cursor_pos
}
pub fn modifiers(&self) -> ModifiersState {
self.key_modifiers
}
pub fn on_window_event(&mut self, event: &WindowEvent) {
match event {
WindowEvent::ModifiersChanged(modifiers) => {
self.key_modifiers = modifiers.state();
}
WindowEvent::CursorMoved { position, .. } => {
self.cursor_pos = PhysicalPoint::new(position.x as f32, position.y as f32);
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
state,
..
},
..
} => {
if state.is_pressed() {
self.keys_pressed.insert(*code);
} else {
self.keys_pressed.remove(code);
}
}
WindowEvent::MouseInput { state, button, .. } => {
if state.is_pressed() {
self.mouse_pressed.insert(*button);
} else {
self.mouse_pressed.remove(button);
}
}
_ => {}
pub fn set_mouse_pressed(&mut self, button: MouseButton, is_pressed: bool) -> bool {
if is_pressed {
self.mouse_pressed.insert(button);
} else {
self.mouse_pressed.remove(&button);
}
}
pub fn is_double_click(&mut self, button: MouseButton) -> bool {
let now = Instant::now();
let last = self.mouse_last_pressed.entry(button);
@@ -81,6 +49,18 @@ impl InputState {
}
}
}
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
self.mouse_pressed.contains(&button)
}
pub fn mouse_pos(&self) -> LogicalPoint<f32> {
self.cursor_pos
}
pub fn set_mouse_pos(&mut self, pos: LogicalPoint<f32>) {
self.cursor_pos = pos;
}
}
pub fn str_as_keycode(s: &str) -> Option<KeyCode> {
@@ -169,104 +149,101 @@ pub fn str_as_keycode(s: &str) -> Option<KeyCode> {
})
}
pub fn keycode_as_str(code: KeyCode) -> Option<String> {
Some(
match code {
// Letters
KeyCode::KeyA => "a",
KeyCode::KeyB => "b",
KeyCode::KeyC => "c",
KeyCode::KeyD => "d",
KeyCode::KeyE => "e",
KeyCode::KeyF => "f",
KeyCode::KeyG => "g",
KeyCode::KeyH => "h",
KeyCode::KeyI => "i",
KeyCode::KeyJ => "j",
KeyCode::KeyK => "k",
KeyCode::KeyL => "l",
KeyCode::KeyM => "m",
KeyCode::KeyN => "n",
KeyCode::KeyO => "o",
KeyCode::KeyP => "p",
KeyCode::KeyQ => "q",
KeyCode::KeyR => "r",
KeyCode::KeyS => "s",
KeyCode::KeyT => "t",
KeyCode::KeyU => "u",
KeyCode::KeyV => "v",
KeyCode::KeyW => "w",
KeyCode::KeyX => "x",
KeyCode::KeyY => "y",
KeyCode::KeyZ => "z",
pub fn keycode_as_str(code: KeyCode) -> Option<&'static str> {
Some(match code {
// Letters
KeyCode::KeyA => "a",
KeyCode::KeyB => "b",
KeyCode::KeyC => "c",
KeyCode::KeyD => "d",
KeyCode::KeyE => "e",
KeyCode::KeyF => "f",
KeyCode::KeyG => "g",
KeyCode::KeyH => "h",
KeyCode::KeyI => "i",
KeyCode::KeyJ => "j",
KeyCode::KeyK => "k",
KeyCode::KeyL => "l",
KeyCode::KeyM => "m",
KeyCode::KeyN => "n",
KeyCode::KeyO => "o",
KeyCode::KeyP => "p",
KeyCode::KeyQ => "q",
KeyCode::KeyR => "r",
KeyCode::KeyS => "s",
KeyCode::KeyT => "t",
KeyCode::KeyU => "u",
KeyCode::KeyV => "v",
KeyCode::KeyW => "w",
KeyCode::KeyX => "x",
KeyCode::KeyY => "y",
KeyCode::KeyZ => "z",
// Digits
KeyCode::Digit0 => "0",
KeyCode::Digit1 => "1",
KeyCode::Digit2 => "2",
KeyCode::Digit3 => "3",
KeyCode::Digit4 => "4",
KeyCode::Digit5 => "5",
KeyCode::Digit6 => "6",
KeyCode::Digit7 => "7",
KeyCode::Digit8 => "8",
KeyCode::Digit9 => "9",
// Digits
KeyCode::Digit0 => "0",
KeyCode::Digit1 => "1",
KeyCode::Digit2 => "2",
KeyCode::Digit3 => "3",
KeyCode::Digit4 => "4",
KeyCode::Digit5 => "5",
KeyCode::Digit6 => "6",
KeyCode::Digit7 => "7",
KeyCode::Digit8 => "8",
KeyCode::Digit9 => "9",
// Modifiers
KeyCode::ShiftLeft => "SHIFT",
KeyCode::ControlLeft => "CTRL",
KeyCode::AltLeft => "ALT",
// Modifiers
KeyCode::ShiftLeft => "SHIFT",
KeyCode::ControlLeft => "CTRL",
KeyCode::AltLeft => "ALT",
// F Keys
KeyCode::F1 => "F1",
KeyCode::F2 => "F2",
KeyCode::F3 => "F3",
KeyCode::F4 => "F4",
KeyCode::F5 => "F5",
KeyCode::F6 => "F6",
KeyCode::F7 => "F7",
KeyCode::F8 => "F8",
KeyCode::F9 => "F9",
KeyCode::F10 => "F10",
KeyCode::F11 => "F11",
KeyCode::F12 => "F12",
// F Keys
KeyCode::F1 => "F1",
KeyCode::F2 => "F2",
KeyCode::F3 => "F3",
KeyCode::F4 => "F4",
KeyCode::F5 => "F5",
KeyCode::F6 => "F6",
KeyCode::F7 => "F7",
KeyCode::F8 => "F8",
KeyCode::F9 => "F9",
KeyCode::F10 => "F10",
KeyCode::F11 => "F11",
KeyCode::F12 => "F12",
// Rest
KeyCode::Space => " ",
KeyCode::Backspace => "BACK",
KeyCode::Tab => "TAB",
KeyCode::Enter => "RETURN",
KeyCode::Escape => "ESCAPE",
KeyCode::Pause => "PAUSE",
KeyCode::PageUp => "PAGEUP",
KeyCode::PageDown => "PAGEDOWN",
KeyCode::End => "END",
KeyCode::Home => "HOME",
KeyCode::PrintScreen => "PRINTSCREEN",
KeyCode::Insert => "INSERT",
KeyCode::Delete => "DELETE",
KeyCode::ArrowUp => "UP",
KeyCode::ArrowDown => "DOWN",
KeyCode::ArrowLeft => "LEFT",
KeyCode::ArrowRight => "RIGHT",
KeyCode::NumLock => "NUMLOCK",
KeyCode::ScrollLock => "SCROLL",
// Rest
KeyCode::Space => " ",
KeyCode::Backspace => "BACK",
KeyCode::Tab => "TAB",
KeyCode::Enter => "RETURN",
KeyCode::Escape => "ESCAPE",
KeyCode::Pause => "PAUSE",
KeyCode::PageUp => "PAGEUP",
KeyCode::PageDown => "PAGEDOWN",
KeyCode::End => "END",
KeyCode::Home => "HOME",
KeyCode::PrintScreen => "PRINTSCREEN",
KeyCode::Insert => "INSERT",
KeyCode::Delete => "DELETE",
KeyCode::ArrowUp => "UP",
KeyCode::ArrowDown => "DOWN",
KeyCode::ArrowLeft => "LEFT",
KeyCode::ArrowRight => "RIGHT",
KeyCode::NumLock => "NUMLOCK",
KeyCode::ScrollLock => "SCROLL",
KeyCode::Equal => "+", // This is what PoB does
KeyCode::Minus => "-",
KeyCode::Comma => ",",
KeyCode::Period => ".",
KeyCode::Slash => "/",
KeyCode::Equal => "+", // This is what PoB does
KeyCode::Minus => "-",
KeyCode::Comma => ",",
KeyCode::Period => ".",
KeyCode::Slash => "/",
KeyCode::NumpadAdd => "+",
KeyCode::NumpadSubtract => "-",
KeyCode::NumpadEnter => "RETURN",
KeyCode::Numpad0 => "0",
KeyCode::NumpadAdd => "+",
KeyCode::NumpadSubtract => "-",
KeyCode::NumpadEnter => "RETURN",
KeyCode::Numpad0 => "0",
_ => return None,
}
.to_string(),
)
_ => return None,
})
}
pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
@@ -280,16 +257,13 @@ pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
})
}
pub fn mousebutton_as_str(button: MouseButton) -> Option<String> {
Some(
match button {
MouseButton::Left => "LEFTBUTTON",
MouseButton::Right => "RIGHTBUTTON",
MouseButton::Middle => "MIDDLEBUTTON",
MouseButton::Back => "MOUSE4",
MouseButton::Forward => "MOUSE5",
_ => return None,
}
.to_string(),
)
pub fn mousebutton_as_str(button: MouseButton) -> Option<&'static str> {
Some(match button {
MouseButton::Left => "LEFTBUTTON",
MouseButton::Right => "RIGHTBUTTON",
MouseButton::Middle => "MIDDLEBUTTON",
MouseButton::Back => "MOUSE4",
MouseButton::Forward => "MOUSE5",
_ => return None,
})
}
+220 -32
View File
@@ -1,31 +1,184 @@
use crate::args::Game;
use crate::{
app::AppState,
args::Game,
color::Srgba,
dpi::{LogicalPoint, LogicalRect},
fonts::{Alignment, LayoutJob},
mode::{AppEvent, ModeFrameOutput, ModeTransition},
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
};
use anyhow::bail;
use flate2::read::GzDecoder;
use regex::Regex;
use std::{
fs::{self},
io::copy,
io::{Write, copy},
path::{Path, PathBuf},
sync::mpsc::{self, Receiver, TryRecvError},
thread,
};
const REPO_NAME: &str = "meehl/rusty-pob-manifest";
pub fn run_installer() -> anyhow::Result<()> {
let script_dir = Game::script_dir();
enum DownloadProgress {
Percentage(f32), // percentage of total size (between 0 and 1)
TotalBytes(u64), // amount of bytes downloaded
}
// run installer iff Launch.lua doesn't exist, meaning this is likely the first run
if script_dir.join("Launch.lua").exists() {
enum Progress {
Download(DownloadProgress),
Complete,
Error(anyhow::Error),
}
enum CurrentProgress {
Starting,
Download(DownloadProgress),
}
/// Execution mode in which PoB's assets are downloaded if they don't exist yet.
///
/// Immediately transitions into PoB mode if assets already exist. Otherwise,
/// it downloads them to the user directory and displays the download progress.
pub struct InstallMode {
progress_rx: Option<Receiver<Progress>>,
current_progress: CurrentProgress,
}
impl InstallMode {
pub fn new() -> 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) {
progress_tx.send(Progress::Error(err)).unwrap();
return;
}
progress_tx.send(Progress::Complete).unwrap();
});
Self {
progress_rx: Some(progress_rx),
current_progress: CurrentProgress::Starting,
}
}
pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
let primitives = self.draw_current_progress(app_state);
Ok(ModeFrameOutput {
primitives,
can_elide: false,
})
}
pub fn update(&mut self, _app_state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
if let Some(progress_rx) = &self.progress_rx {
loop {
match progress_rx.try_recv() {
Ok(Progress::Download(progress)) => {
self.current_progress = CurrentProgress::Download(progress);
}
Ok(Progress::Complete) => {
return Ok(Some(ModeTransition::PoB));
}
Ok(Progress::Error(err)) => {
return Err(anyhow::anyhow!("Download failed: {}", err));
}
Err(TryRecvError::Disconnected) => {
return Err(anyhow::anyhow!("Download thread disconnected!"));
}
Err(TryRecvError::Empty) => {
break;
}
}
}
}
Ok(None)
}
pub fn handle_event(
&mut self,
_app_state: &mut AppState,
_event: AppEvent,
) -> anyhow::Result<()> {
Ok(())
}
fn draw_current_progress(
&self,
app_state: &mut AppState,
) -> Box<dyn Iterator<Item = ClippedPrimitive>> {
let mut job = LayoutJob::new(
parley::GenericFamily::SansSerif,
32.0,
34.0,
Some(Alignment::Center),
Some(700.0),
);
let progress_text = match &self.current_progress {
CurrentProgress::Starting => String::from("Starting download..."),
CurrentProgress::Download(progress) => match progress {
DownloadProgress::Percentage(progress) => {
let percent = (progress * 100.0) as u32;
format!("Downloading assets... ({})", percent)
}
DownloadProgress::TotalBytes(total_bytes) => {
format!("Downloading assets... ({})", format_bytes(*total_bytes))
}
},
};
job.append(&progress_text, Srgba::WHITE);
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>();
let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0);
let primitive = TextPrimitive::new(pos, layout);
let clipped_primitive = ClippedPrimitive {
clip_rect: LogicalRect::from_size(app_state.window.logical_size().cast()),
primitive: DrawPrimitive::Text(primitive),
};
let primitives = vec![clipped_primitive];
Box::new(primitives.into_iter())
}
}
fn install<P: AsRef<Path>>(
target_dir: P,
progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> {
// Skip installation if version file exists
let version_file_path = target_dir.as_ref().join("rpob.version");
if version_file_path.exists() {
return Ok(());
}
download_path_of_building(script_dir.as_path())?;
replace_manifest(script_dir.as_path())?;
download_path_of_building(&target_dir, progress_tx)?;
replace_updatecheck(&target_dir)?;
set_branch_and_platform(&target_dir)?;
// write version file
let mut version_file = fs::File::create(version_file_path)?;
let pkg_version = env!("CARGO_PKG_VERSION");
version_file.write_all(pkg_version.as_bytes())?;
Ok(())
}
/// Download latest release of Path of Building
fn download_path_of_building<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
println!("Downloading latest release of Path of Building...");
/// Downloads latest release of Path of Building
fn download_path_of_building<P: AsRef<Path>>(
target_dir: P,
progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> {
log::info!("Downloading Path of Building assets...");
let repo = match Game::current() {
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
@@ -37,9 +190,14 @@ fn download_path_of_building<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()
);
let mut response = ureq::get(url).call()?;
let body_reader = response.body_mut().as_reader();
let total_size = response
.headers()
.get("Content-Length")
.and_then(|s| s.to_str().ok()?.parse::<u64>().ok());
let body_reader = response.body_mut().as_reader();
let mut archive = tar::Archive::new(GzDecoder::new(body_reader));
let mut downloaded = 0u64;
for file in archive.entries()? {
let mut file = file?;
@@ -85,34 +243,28 @@ fn download_path_of_building<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()
}
file.unpack(&target_path)?;
}
downloaded += file.size();
if let Some(total) = total_size {
let progress = downloaded as f32 / total as f32;
progress_tx.send(Progress::Download(DownloadProgress::Percentage(progress)))?;
} else {
progress_tx.send(Progress::Download(DownloadProgress::TotalBytes(downloaded)))?;
}
}
Ok(())
}
/// Replace manifest and UpdateCheck with rusty-path-of-building's modified versions
/// This is needed to make updating work without writing our own update system.
fn replace_manifest<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
log::info!("Replacing manifest...");
let game_path = match Game::current() {
Game::Poe1 => "poe1",
Game::Poe2 => "poe2",
};
// Download on overwrite files
download_file(
&format!(
"https://raw.githubusercontent.com/{REPO_NAME}/master/{}/{}",
game_path, "manifest.xml"
),
target_dir.as_ref().join("manifest.xml"),
)?;
/// Replaces UpdateCheck with rusty-path-of-building's custom version of it.
fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
log::info!("Downloading custom UpdateCheck.lua script...");
download_file(
&format!(
"https://raw.githubusercontent.com/{REPO_NAME}/master/{}/{}",
game_path, "UpdateCheck.lua"
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
"UpdateCheck.lua"
),
target_dir.as_ref().join("UpdateCheck.lua"),
)?;
@@ -120,6 +272,26 @@ fn replace_manifest<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
Ok(())
}
/// Sets branch and platform in manifest.xml
fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
let filename = target_dir.as_ref().join("manifest.xml");
let manifest = fs::read_to_string(&filename)?;
#[cfg(not(target_os = "windows"))]
let platform = std::env::consts::OS;
#[cfg(target_os = "windows")]
let platform = "win32";
let new_version = format!(r#"<Version branch="master" platform="{}""#, platform);
let version_regex = Regex::new(r"<Version").unwrap();
let new_manifest = version_regex.replace(&manifest, new_version);
fs::write(&filename, new_manifest.as_ref())?;
Ok(())
}
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
let mut response = ureq::get(url).call()?;
@@ -132,3 +304,19 @@ fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()>
bail!("Unable to download: {}", url);
}
}
fn format_bytes(size_in_bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
const GB: u64 = MB * 1024;
if size_in_bytes >= GB {
format!("{:.2} GB", size_in_bytes as f64 / GB as f64)
} else if size_in_bytes >= MB {
format!("{:.2} MB", size_in_bytes as f64 / MB as f64)
} else if size_in_bytes >= KB {
format!("{:.2} KB", size_in_bytes as f64 / KB as f64)
} else {
format!("{} bytes", size_in_bytes)
}
}
+65 -14
View File
@@ -1,11 +1,17 @@
use std::collections::BTreeMap;
use crate::{
dpi::LogicalRect,
math::Rect,
renderer::primitives::{
ClippedPrimitive, DrawPrimitive, QuadPrimitive, RectPrimitive, TextPrimitive,
color::Srgba,
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad, NormalizedRect},
fonts::Layout,
renderer::{
primitives::{
ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive,
RectTexture, TextPrimitive,
},
textures::TextureId,
},
util::calculate_hash,
};
/// Holds the draw primitives for each layer.
@@ -13,36 +19,35 @@ use crate::{
/// Adding a primitive places it in currently set layer. Positions are interpreted as being relative to
/// the current viewport. They are translated into absolute positions (screen positions) and
/// clipped by the viewport.
#[derive(Default)]
pub struct Layers {
layers: BTreeMap<(i32, i32), Vec<ClippedPrimitive>>,
current_layer: (i32, i32),
viewport: LogicalRect<f32>,
current_draw_color: Srgba,
}
impl Layers {
pub fn new() -> Self {
Self {
layers: Default::default(),
current_layer: (0, 0),
viewport: Rect::zero(),
}
}
pub fn reset(&mut self) {
self.current_layer = (0, 0);
self.layers.clear();
self.current_draw_color = Srgba::TRANSPARENT;
}
/// Consume primitives and return an iterator over them in drawing order.
pub fn consume_layers(&mut self) -> impl Iterator<Item = ClippedPrimitive> {
pub fn consume_layers(&mut self) -> Box<dyn Iterator<Item = ClippedPrimitive>> {
let layers = std::mem::take(&mut self.layers);
layers.into_values().flatten()
Box::new(layers.into_values().flatten())
}
pub fn set_viewport(&mut self, viewport: LogicalRect<f32>) {
self.viewport = viewport;
}
pub fn set_viewport_from_size(&mut self, size: LogicalSize<u32>) {
self.set_viewport(LogicalRect::from_size(size).cast());
}
pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) {
self.current_layer = (layer, sublayer);
}
@@ -51,6 +56,48 @@ impl Layers {
self.set_draw_layer(self.current_layer.0, sublayer);
}
pub fn set_draw_color(&mut self, color: Srgba) {
self.current_draw_color = color;
}
pub fn get_draw_color(&self) -> Srgba {
self.current_draw_color
}
pub fn draw_rect(
&mut self,
texture_id: Option<TextureId>,
rect: LogicalRect<f32>,
uv: NormalizedRect,
layer_idx: u32,
) {
let texture = texture_id.map(|id| RectTexture::new(id, uv, layer_idx));
let primitive = RectPrimitive::new(rect, self.current_draw_color, texture);
self.add_rect(primitive);
}
pub fn draw_quad(
&mut self,
texture_id: Option<TextureId>,
quad: LogicalQuad<f32>,
uv: NormalizedQuad,
layer_idx: u32,
) {
let texture = texture_id.map(|id| QuadTexture::new(id, uv, layer_idx));
let primitive = QuadPrimitive::new(quad, self.current_draw_color, texture);
self.add_quad(primitive);
}
pub fn draw_text(
&mut self,
position: LogicalPoint<f32>,
layout: std::sync::Arc<Layout>,
is_absolute_position: bool,
) {
let primitive = TextPrimitive::new(position, layout);
self.add_text(primitive, is_absolute_position);
}
pub fn add_rect(&mut self, mut rect: RectPrimitive) {
rect.translate(self.viewport.min.to_vector());
@@ -93,6 +140,10 @@ impl Layers {
.or_default()
.push(clipped_primitive);
}
pub fn get_hash(&self) -> u64 {
calculate_hash(self)
}
}
impl std::hash::Hash for Layers {
+200 -60
View File
@@ -1,16 +1,159 @@
use std::{cell::RefCell, rc::Rc};
use clap::Parser;
use mlua::{Lua, Result as LuaResult, Table};
use crate::{
Game,
api::{self, get_callback},
app::AppState,
args::Args,
fonts::Fonts,
input::InputState,
layers::Layers,
pob::PoBState,
renderer::textures::WrappedTextureManager,
subscript::{NativeMultiValue, SubscriptManager, SubscriptResult, register_subscript_globals},
util::change_working_directory,
window::WindowState,
};
use arboard::Clipboard;
use clap::Parser;
use mlua::{Lua, Result as LuaResult, Table};
use std::{
cell::{Cell, RefCell},
path::PathBuf,
rc::Rc,
};
macro_rules! socket_accessor {
($field:ident: & $ty:ty) => {
pub fn $field(&self) -> &$ty {
let ptr = self.$field.get();
assert!(!ptr.is_null());
unsafe { &*ptr }
}
};
($field:ident: &mut $ty:ty) => {
#[allow(clippy::mut_from_ref)]
pub fn $field(&self) -> &mut $ty {
let ptr = self.$field.get();
assert!(!ptr.is_null());
unsafe { &mut *ptr }
}
};
}
/// A collection of pointers needed by the API funtions.
///
/// Before executing any lua code, we need to "plug" the [`PoBContext`] into
/// the ContextSocket and "unplug" them afterwards.
pub struct ContextSocket {
window: Cell<*const WindowState>,
input: Cell<*const InputState>,
fonts: Cell<*mut Fonts>,
texture_manager: Cell<*mut WrappedTextureManager>,
clipboard: Cell<*mut Clipboard>,
current_working_dir: Cell<*mut PathBuf>,
layers: Cell<*mut Layers>,
needs_restart: Cell<*mut bool>,
is_dpi_aware: Cell<*mut bool>,
}
impl ContextSocket {
pub fn new() -> &'static Self {
Box::leak(Box::new(Self {
window: Cell::new(std::ptr::null()),
input: Cell::new(std::ptr::null()),
fonts: Cell::new(std::ptr::null_mut()),
texture_manager: Cell::new(std::ptr::null_mut()),
clipboard: Cell::new(std::ptr::null_mut()),
current_working_dir: Cell::new(std::ptr::null_mut()),
layers: Cell::new(std::ptr::null_mut()),
needs_restart: Cell::new(std::ptr::null_mut()),
is_dpi_aware: Cell::new(std::ptr::null_mut()),
}))
}
pub fn set(&self, ctx: &mut PoBContext) {
self.window.set(&ctx.app.window);
self.input.set(&ctx.app.input);
self.fonts.set(&mut ctx.app.fonts);
self.texture_manager.set(&mut ctx.app.texture_manager);
self.clipboard.set(&mut ctx.app.clipboard);
self.current_working_dir
.set(&mut ctx.pob.current_working_dir);
self.layers.set(&mut ctx.pob.layers);
self.needs_restart.set(&mut ctx.pob.needs_restart);
self.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware);
}
pub fn clear(&self) {
self.window.set(std::ptr::null());
self.input.set(std::ptr::null());
self.fonts.set(std::ptr::null_mut());
self.texture_manager.set(std::ptr::null_mut());
self.clipboard.set(std::ptr::null_mut());
self.current_working_dir.set(std::ptr::null_mut());
self.layers.set(std::ptr::null_mut());
self.needs_restart.set(std::ptr::null_mut());
self.is_dpi_aware.set(std::ptr::null_mut());
}
socket_accessor!(window: &WindowState);
socket_accessor!(input: &InputState);
socket_accessor!(fonts: &mut Fonts);
socket_accessor!(texture_manager: &mut WrappedTextureManager);
socket_accessor!(clipboard: &mut Clipboard);
socket_accessor!(current_working_dir: &mut PathBuf);
socket_accessor!(layers: &mut Layers);
socket_accessor!(needs_restart: &mut bool);
socket_accessor!(is_dpi_aware: &mut bool);
}
pub enum PoBEvent {
Init,
Exit,
Frame,
KeyDown(&'static str, bool),
KeyUp(&'static str),
Char(char),
SubFinished {
id: u64,
return_values: NativeMultiValue,
},
SubError {
id: u64,
error: String,
},
}
impl std::fmt::Display for PoBEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PoBEvent::Init => write!(f, "Init"),
PoBEvent::Exit => write!(f, "Exit"),
PoBEvent::Frame => write!(f, "Frame"),
PoBEvent::KeyDown(_, _) => write!(f, "KeyDown"),
PoBEvent::KeyUp(_) => write!(f, "KeyUp"),
PoBEvent::Char(_) => write!(f, "Char"),
PoBEvent::SubFinished { .. } => write!(f, "SubFinished"),
PoBEvent::SubError { .. } => write!(f, "SubError"),
}
}
}
pub struct PoBContext<'a> {
pub app: &'a mut AppState,
pub pob: &'a mut PoBState,
}
impl<'a> PoBContext<'a> {
pub fn new(app_state: &'a mut AppState, pob_state: &'a mut PoBState) -> Self {
Self {
app: app_state,
pob: pob_state,
}
}
}
/// Lua instance that runs the PoB application code and manages subscripts.
pub struct LuaInstance {
lua: Lua,
subscript_manager: Rc<RefCell<SubscriptManager>>,
@@ -23,14 +166,10 @@ impl LuaInstance {
let lua = Self::create_lua_state()?;
register_subscript_globals(&lua, &subscript_manager)?;
let instance = Self {
Ok(Self {
lua,
subscript_manager,
};
instance.init()?;
Ok(instance)
})
}
fn create_lua_state() -> LuaResult<Lua> {
@@ -42,90 +181,91 @@ impl LuaInstance {
let args_table = lua.create_sequence_from(std::iter::once(args.build_path))?;
lua.globals().set("arg", args_table)?;
// add ./lua to package.path and package.cpath
Self::register_package_paths(&lua)?;
// register "socket"
let socket = ContextSocket::new();
lua.set_app_data(socket);
// register callbacks
api::register_globals(&lua)?;
Ok(lua)
}
pub fn init(&self) -> LuaResult<()> {
/// Loads and executes PoB's Launch.lua script
pub fn launch(&self, ctx: &mut PoBContext) -> LuaResult<()> {
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap();
socket.set(ctx);
let script_dir = Game::script_dir();
change_working_directory(script_dir.as_path())?;
self.load(script_dir.join("Launch.lua")).exec()?;
self.on_init()?;
socket.clear();
Ok(())
}
pub fn restart(&mut self) -> LuaResult<()> {
pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> {
self.lua = Self::create_lua_state()?;
register_subscript_globals(&self.lua, &self.subscript_manager)?;
self.init()?;
self.launch(ctx)?;
Ok(())
}
/// Run functions for subscripts and handle their completion/failure.
pub fn handle_subscripts(&self) {
pub fn handle_subscripts(&self, ctx: &mut PoBContext) {
profiling::scope!("handle_subscripts");
let subscript_events = self.subscript_manager.borrow_mut().process(self);
// Handle finished/errored subscripts.
for event in subscript_events {
match event {
SubscriptResult::SubscriptFinished { id, return_values } => {
self.on_sub_finished(id, return_values).unwrap();
self.handle_event(PoBEvent::SubFinished { id, return_values }, ctx)
.unwrap();
}
SubscriptResult::SubscriptError { id, error } => {
self.on_sub_error(id, &error).unwrap();
self.handle_event(PoBEvent::SubError { id, error }, ctx)
.unwrap();
}
}
}
}
fn on_init(&self) -> LuaResult<()> {
let on_init = get_callback(&self.lua, "OnInit")?;
on_init.call::<()>(())
}
pub fn on_frame(&self) -> LuaResult<()> {
profiling::scope!("on_frame");
let on_frame = get_callback(&self.lua, "OnFrame")?;
on_frame.call::<()>(())
}
pub fn on_char(&self, ch: &str) -> LuaResult<()> {
let on_char = get_callback(&self.lua, "OnChar")?;
on_char.call::<()>(ch)
}
pub fn on_key_down(&self, key: &str, is_double_click: bool) -> LuaResult<()> {
let on_key_down = get_callback(&self.lua, "OnKeyDown")?;
on_key_down.call::<()>((key, is_double_click))
}
pub fn on_key_up(&self, key: &str) -> LuaResult<()> {
let on_key_up = get_callback(&self.lua, "OnKeyUp")?;
on_key_up.call::<()>(key)
}
pub fn on_sub_finished(&self, id: u64, return_values: NativeMultiValue) -> LuaResult<()> {
let on_sub_finished = get_callback(&self.lua, "OnSubFinished")?;
on_sub_finished.call::<()>((id, return_values))
}
pub fn on_sub_error(&self, id: u64, error: &str) -> LuaResult<()> {
let on_sub_error = get_callback(&self.lua, "OnSubError")?;
on_sub_error.call::<()>((id, error))
}
pub fn on_exit(&self) -> LuaResult<()> {
let on_exit = get_callback(&self.lua, "OnExit")?;
on_exit.call::<()>(())
pub fn handle_event(&self, event: PoBEvent, ctx: &mut PoBContext) -> LuaResult<()> {
profiling::scope!("handle_event", format!("{}", event));
// "Plug" references into "socket"
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap();
socket.set(ctx);
// Call event handler in PoB application code
let handler_result = match event {
PoBEvent::Init => get_callback(&self.lua, "OnInit")?.call::<()>(()),
PoBEvent::Exit => get_callback(&self.lua, "OnExit")?.call::<()>(()),
PoBEvent::Frame => get_callback(&self.lua, "OnFrame")?.call::<()>(()),
PoBEvent::KeyDown(key, double_click) => {
get_callback(&self.lua, "OnKeyDown")?.call::<()>((key, double_click))
}
PoBEvent::KeyUp(key) => get_callback(&self.lua, "OnKeyUp")?.call::<()>(key),
PoBEvent::Char(ch) => get_callback(&self.lua, "OnChar")?.call::<()>(ch),
PoBEvent::SubFinished { id, return_values } => {
get_callback(&self.lua, "OnSubFinished")?.call::<()>((id, return_values))
}
PoBEvent::SubError { id, error } => {
get_callback(&self.lua, "OnSubError")?.call::<()>((id, error))
}
};
// "Unplug" references from "socket"
socket.clear();
handler_result
}
/// Adds "${script_dir}/lua" to package path
pub fn register_package_paths(lua: &Lua) -> LuaResult<()> {
let script_dir = Game::script_dir();
let package: Table = lua.globals().get("package")?;
+7 -6
View File
@@ -1,6 +1,7 @@
use crate::app::App;
use crate::args::{Args, Game};
use crate::installer::run_installer;
use crate::{
app::App,
args::{Args, Game},
};
use clap::Parser;
use winit::event_loop::EventLoop;
@@ -8,7 +9,6 @@ mod api;
mod app;
mod args;
mod color;
mod context;
mod dpi;
mod fonts;
mod gfx;
@@ -17,9 +17,12 @@ mod installer;
mod layers;
mod lua;
mod math;
mod mode;
mod pob;
mod renderer;
mod subscript;
mod util;
mod window;
mod worker_pool;
fn main() -> anyhow::Result<()> {
@@ -38,8 +41,6 @@ fn main() -> anyhow::Result<()> {
let args = Args::parse();
Game::init(args.game);
run_installer()?;
let mut app = App::new()?;
let event_loop = EventLoop::with_user_event().build()?;
+65
View File
@@ -0,0 +1,65 @@
use crate::{
app::AppState, installer::InstallMode, pob::PoBMode, renderer::primitives::ClippedPrimitive,
};
use winit::{event::MouseButton, keyboard::KeyCode};
pub enum AppEvent {
KeyDown {
code: KeyCode,
},
KeyUp {
code: KeyCode,
},
MouseDown {
button: MouseButton,
is_double_click: bool,
},
MouseUp {
button: MouseButton,
},
MouseWheel {
delta: f32,
},
CharacterInput {
ch: char,
},
Exit,
}
/// Represents the transition to another mode
pub enum ModeTransition {
PoB,
}
pub struct ModeFrameOutput {
pub primitives: Box<dyn Iterator<Item = ClippedPrimitive>>,
pub can_elide: bool,
}
pub enum AppMode {
Install(InstallMode),
PoB(PoBMode),
}
impl AppMode {
pub fn frame(&mut self, state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
match self {
AppMode::Install(mode) => mode.frame(state),
AppMode::PoB(mode) => mode.frame(state),
}
}
pub fn update(&mut self, state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
match self {
AppMode::Install(mode) => mode.update(state),
AppMode::PoB(mode) => mode.update(state),
}
}
pub fn handle_event(&mut self, state: &mut AppState, event: AppEvent) -> anyhow::Result<()> {
match self {
AppMode::Install(mode) => mode.handle_event(state, event),
AppMode::PoB(mode) => mode.handle_event(state, event),
}
}
}
+145
View File
@@ -0,0 +1,145 @@
use crate::{
app::AppState,
dpi::{LogicalRect, LogicalSize},
input::{keycode_as_str, mousebutton_as_str},
layers::Layers,
lua::{LuaInstance, PoBContext, PoBEvent},
mode::{AppEvent, ModeFrameOutput, ModeTransition},
};
use std::path::PathBuf;
pub struct PoBState {
pub layers: Layers,
pub current_working_dir: PathBuf,
pub needs_restart: bool,
pub is_dpi_aware: bool,
}
/// Execution mode in which PoB's application code is run.
///
/// It forwards app events to PoB's application event handlers and outputs
/// the draw primitives created by PoB each frame.
pub struct PoBMode {
lua_instance: LuaInstance,
state: PoBState,
previous_layers_hash: u64,
}
impl PoBMode {
pub fn new(app_state: &mut AppState) -> anyhow::Result<Self> {
let mut state = PoBState {
layers: Layers::default(),
current_working_dir: PathBuf::default(),
needs_restart: false,
is_dpi_aware: false,
};
let lua_instance = LuaInstance::new()?;
let mut pob_ctx = PoBContext::new(app_state, &mut state);
lua_instance.launch(&mut pob_ctx)?;
lua_instance.handle_event(PoBEvent::Init, &mut pob_ctx)?;
Ok(Self {
lua_instance,
state,
previous_layers_hash: Default::default(),
})
}
pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
profiling::scope!("frame");
// reset layers and viewport
self.state.layers.reset();
self.reset_viewport(app_state.window.logical_size());
let mut ctx = PoBContext::new(app_state, &mut self.state);
// handle subscripts
self.lua_instance.handle_subscripts(&mut ctx);
// run PoB's draw code.
// this will "fill up" up the layers with draw primitives
self.lua_instance.handle_event(PoBEvent::Frame, &mut ctx)?;
// check if draw prmitives are identical to primitives from last frame
let layers_hash = self.state.layers.get_hash();
let identical = layers_hash == self.previous_layers_hash;
self.previous_layers_hash = layers_hash;
Ok(ModeFrameOutput {
primitives: self.state.layers.consume_layers(),
can_elide: identical,
})
}
pub fn update(&mut self, app_state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
if self.state.needs_restart {
let mut ctx = PoBContext::new(app_state, &mut self.state);
self.lua_instance.restart(&mut ctx)?;
self.lua_instance.handle_event(PoBEvent::Init, &mut ctx)?;
self.state.needs_restart = false;
}
Ok(None)
}
pub fn handle_event(
&mut self,
app_state: &mut AppState,
event: AppEvent,
) -> anyhow::Result<()> {
let mut ctx = PoBContext::new(app_state, &mut self.state);
match event {
AppEvent::KeyDown { code } => {
if let Some(key_string) = keycode_as_str(code) {
let pob_event = PoBEvent::KeyDown(key_string, false);
self.lua_instance.handle_event(pob_event, &mut ctx)?;
}
}
AppEvent::KeyUp { code } => {
if let Some(key_string) = keycode_as_str(code) {
let pob_event = PoBEvent::KeyUp(key_string);
self.lua_instance.handle_event(pob_event, &mut ctx)?;
}
}
AppEvent::MouseDown {
button,
is_double_click,
} => {
if let Some(button_string) = mousebutton_as_str(button) {
let pob_event = PoBEvent::KeyDown(button_string, is_double_click);
self.lua_instance.handle_event(pob_event, &mut ctx)?;
}
}
AppEvent::MouseUp { button } => {
if let Some(button_string) = mousebutton_as_str(button) {
let pob_event = PoBEvent::KeyUp(button_string);
self.lua_instance.handle_event(pob_event, &mut ctx)?;
}
}
AppEvent::MouseWheel { delta } => {
if delta > 0.0 {
self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELUP"), &mut ctx)?;
} else if delta < 0.0 {
self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELDOWN"), &mut ctx)?;
}
}
AppEvent::CharacterInput { ch } => {
self.lua_instance
.handle_event(PoBEvent::Char(ch), &mut ctx)?;
}
AppEvent::Exit => self.lua_instance.handle_event(PoBEvent::Exit, &mut ctx)?,
}
Ok(())
}
fn reset_viewport(&mut self, size: LogicalSize<u32>) {
self.state
.layers
.set_viewport(LogicalRect::from_size(size).cast());
}
}
+70 -51
View File
@@ -107,65 +107,84 @@ impl std::fmt::Debug for ImageData {
}
}
// TODO: clean this up
pub fn load_image_file<P: AsRef<Path>>(path: P) -> anyhow::Result<ImageData> {
// PoB2 assumes a case insensitive filesystem is used. This can lead to some
// files not being found on case sensitive systems.
// As a workaround, try using a lower-cased path if the original path doesn't
// exist.
let path = if path.as_ref().exists() {
path.as_ref().to_owned()
} else {
let mut path = path.as_ref().to_owned();
let lowercase_filename = path.file_name().unwrap().to_ascii_lowercase();
path.set_file_name(lowercase_filename);
path
};
let path = resolve_path(path);
// special handling for compressed dds files
if path.extension().and_then(|s| s.to_str()) == Some("zst")
if is_compressed_dds(&path) {
load_compressed_dds(&path)
} else {
// let image crate deal with other file types
let image = image::ImageReader::open(&path)?.decode()?;
Ok(image.into())
}
}
/// Attempts to find the file, trying lowercase filename if it doesn't exist.
///
/// NOTE: PoB2 assumes a case insensitive filesystem, so checking the lowercase name
/// helps on case sensitive systems in some cases (no pun intended).
fn resolve_path<P: AsRef<Path>>(path: P) -> std::path::PathBuf {
let path_ref = path.as_ref();
if path_ref.exists() {
return path_ref.to_owned();
}
let mut lowercase_path = path_ref.to_owned();
if let Some(filename) = path_ref.file_name() {
lowercase_path.set_file_name(filename.to_ascii_lowercase());
}
lowercase_path
}
/// Checks if file is a compressed DDS file (.dds.zst)
fn is_compressed_dds<P: AsRef<Path>>(path: P) -> bool {
let path = path.as_ref();
path.extension().and_then(|s| s.to_str()) == Some("zst")
&& path
.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.ends_with(".dds"))
.unwrap_or(false)
{
let f = std::fs::File::open(&path)?;
let file_len = f.metadata().ok().map(|m| m.len());
let mut zstd_decoder = zstd::Decoder::new(f)?;
.is_some_and(|s| s.ends_with(".dds"))
}
let parse_option = dds::header::ParseOptions::new_permissive(file_len);
let header = dds::header::Header::read(&mut zstd_decoder, &parse_option)?;
let dxgi_format = dds::Format::from_header(&header)?;
// zstd_decoder will now be at start of pixel data
let non_data_len = dds::header::Header::MAGIC.len() + header.byte_len();
let data_len = file_len.and_then(|l| (l as usize).checked_sub(non_data_len));
let mut pixel_data = Vec::with_capacity(data_len.unwrap_or(0));
zstd_decoder.read_to_end(&mut pixel_data)?;
fn dds_format_to_wgpu(format: dds::Format) -> anyhow::Result<wgpu::TextureFormat> {
Ok(match format {
dds::Format::BC1_UNORM => wgpu::TextureFormat::Bc1RgbaUnorm,
dds::Format::BC2_UNORM => wgpu::TextureFormat::Bc2RgbaUnorm,
dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm,
dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm,
dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm,
_ => anyhow::bail!("Unsupported DDS format: {:?}", format),
})
}
let format = match dxgi_format {
dds::Format::BC1_UNORM => wgpu::TextureFormat::Bc1RgbaUnorm,
dds::Format::BC2_UNORM => wgpu::TextureFormat::Bc2RgbaUnorm,
dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm,
dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm,
dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm,
_ => anyhow::bail!("Unsupported dxgi format"),
};
/// Loads a compressed DDS file (.dds.zst)
fn load_compressed_dds<P: AsRef<Path>>(path: P) -> anyhow::Result<ImageData> {
let file = std::fs::File::open(path.as_ref())?;
let file_len = file.metadata().ok().map(|m| m.len());
let image_data = ImageData {
format,
width: header.width(),
height: header.height(),
array_layers: header.array_size(),
mipmap_count: header.mipmap_count(),
data_order: DataOrder::LayerMajor,
bytes: pixel_data,
};
let mut decoder = zstd::Decoder::new(file)?;
return Ok(image_data);
}
let parse_options = dds::header::ParseOptions::new_permissive(file_len);
let header = dds::header::Header::read(&mut decoder, &parse_options)?;
let dxgi_format = dds::Format::from_header(&header)?;
// zstd_decoder will now be at start of pixel data
// let image crate deal with other file types
let image = image::ImageReader::open(&path)?.decode()?;
Ok(image.into())
// Read pixel data
let non_data_len = dds::header::Header::MAGIC.len() + header.byte_len();
let expected_data_len = file_len
.and_then(|len| (len as usize).checked_sub(non_data_len))
.unwrap_or(0);
let mut pixel_data = Vec::with_capacity(expected_data_len);
decoder.read_to_end(&mut pixel_data)?;
Ok(ImageData {
format: dds_format_to_wgpu(dxgi_format)?,
width: header.width(),
height: header.height(),
array_layers: header.array_size(),
mipmap_count: header.mipmap_count(),
data_order: DataOrder::LayerMajor,
bytes: pixel_data,
})
}
+51
View File
@@ -0,0 +1,51 @@
use std::sync::Arc;
use winit::window::Window;
use crate::dpi::{ConvertToLogical, LogicalSize, PhysicalSize};
pub struct WindowState {
pub window: Option<Arc<Window>>,
pub size: PhysicalSize<u32>,
pub scale_factor: f32,
pending_window_title: std::cell::Cell<Option<String>>,
}
impl Default for WindowState {
fn default() -> Self {
Self {
window: None,
size: Default::default(),
scale_factor: 1.0,
pending_window_title: std::cell::Cell::new(None),
}
}
}
impl WindowState {
pub fn set_window(&mut self, window: Arc<Window>) {
if let Some(title) = self.pending_window_title.take() {
window.set_title(&title);
}
self.window = Some(window);
}
pub fn set_window_title(&self, title: &str) {
if let Some(ref window) = self.window {
window.set_title(title);
} else {
self.pending_window_title.set(Some(title.to_string()));
}
}
pub fn logical_size(&self) -> LogicalSize<u32> {
self.size.to_logical(self.scale_factor)
}
pub fn focus(&self) {
if let Some(ref window) = self.window {
window.focus_window();
}
}
}