diff --git a/CHANGELOG.md b/CHANGELOG.md index e064f9c..d36ef59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## [Unreleased] - ReleaseDate +### Added + +- Add visual indicator for download progress in installer + +### Changed + +- Remove global context + ## [0.1.2] - 2025-10-20 ### Fixed @@ -33,8 +41,8 @@ - First release -[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.1.2...HEAD [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 diff --git a/src/api.rs b/src/api.rs index afb95b4..ec45919 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,219 +1,107 @@ -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_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)?)?; + // 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)?)?; + + // 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 { - 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 { - 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> { - 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 { - Ok(Game::script_dir()) -} - -// parent directory of executable -fn get_runtime_path(_: &Lua, _: ()) -> LuaResult { - 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::((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::() { - 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)) -> LuaResult<()> { - print_table(&table, 0, !no_recursive.unwrap_or(true))?; - Ok(()) -} - -fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult { - match func.call::(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 { Ok(SystemTime::now() .duration_since(UNIX_EPOCH) @@ -221,174 +109,13 @@ fn get_time(_l: &Lua, _: ()) -> LuaResult { .as_millis()) } -fn make_dir(l: &Lua, path: String) -> LuaResult { - 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 { Ok(PoBString(&text).strip_escapes()) } -fn inflate(l: &Lua, compressed: LuaString) -> LuaResult { - 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 { - 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), -) -> LuaResult { - 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 { - 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 { - 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 { - 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 { - 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 { - 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::(args); - CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?; - result -} - -fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult { - 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::(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 { - 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 +126,7 @@ fn open_url(l: &Lua, url: String) -> LuaResult { } } +// TODO: handle "DPI_AWARE" flag fn render_init(_: &Lua, _features: Variadic) -> LuaResult<()> { Ok(()) } diff --git a/src/api/callback.rs b/src/api/callback.rs new file mode 100644 index 0000000..92d6d48 --- /dev/null +++ b/src/api/callback.rs @@ -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 { + 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 { + let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?; + let callback_function: Function = callback_table.get(name)?; + Ok(callback_function) +} diff --git a/src/api/clipboard.rs b/src/api/clipboard.rs new file mode 100644 index 0000000..bb5c7bf --- /dev/null +++ b/src/api/clipboard.rs @@ -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 { + let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); + let text = socket + .clipboard() + .get_text() + .map_err(|e| anyhow::anyhow!("{}", e))?; + Ok(text) +} diff --git a/src/api/compression.rs b/src/api/compression.rs new file mode 100644 index 0000000..44ba825 --- /dev/null +++ b/src/api/compression.rs @@ -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 { + 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 { + 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()), + } +} diff --git a/src/api/console.rs b/src/api/console.rs new file mode 100644 index 0000000..9d714ed --- /dev/null +++ b/src/api/console.rs @@ -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::((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), +) -> 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::() { + 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(()) +} diff --git a/src/api/image_handle.rs b/src/api/image_handle.rs index d3cde06..4f95826 100644 --- a/src/api/image_handle.rs +++ b/src/api/image_handle.rs @@ -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 { + Ok(ImageHandle::Unloaded) +} #[derive(Clone)] pub enum ImageHandle { @@ -13,52 +16,7 @@ pub enum ImageHandle { impl UserData for ImageHandle { fn add_methods>(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(()) +} diff --git a/src/api/input.rs b/src/api/input.rs new file mode 100644 index 0000000..fd80b99 --- /dev/null +++ b/src/api/input.rs @@ -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 { + 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) + } +} diff --git a/src/api/lua.rs b/src/api/lua.rs new file mode 100644 index 0000000..5951bb6 --- /dev/null +++ b/src/api/lua.rs @@ -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 { + match func.call::(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 { + 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::(args); + change_working_directory(current_dir)?; + result +} + +pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult { + 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::(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 +} diff --git a/src/api/paths.rs b/src/api/paths.rs new file mode 100644 index 0000000..8cff871 --- /dev/null +++ b/src/api/paths.rs @@ -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> { + 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 { + Ok(Game::script_dir()) +} + +// parent directory of executable +pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult { + match get_executable_dir() { + Ok(exe_path) => Ok(exe_path), + Err(_) => Ok(PathBuf::new()), + } +} + +pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult { + 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 { + 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)?), + } +} diff --git a/src/api/rendering.rs b/src/api/rendering.rs index 32123fa..a07e249 100644 --- a/src/api/rendering.rs +++ b/src/api/rendering.rs @@ -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 { //profiling::scope!("get_char_index_at_cur"); + let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); let font_type = font_type.parse::()?; 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) diff --git a/src/api/search_handle.rs b/src/api/search_handle.rs index 7a96164..b60695e 100644 --- a/src/api/search_handle.rs +++ b/src/api/search_handle.rs @@ -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), +) -> LuaResult { + 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, diff --git a/src/api/window.rs b/src/api/window.rs new file mode 100644 index 0000000..47b83d7 --- /dev/null +++ b/src/api/window.rs @@ -0,0 +1,21 @@ +use crate::lua::ContextSocket; +use mlua::{Lua, Result as LuaResult}; + +// NOTE: needs to return physical size if this MR gets merged: +// https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2/pull/1420 +pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { + let socket = l.app_data_ref::<&'static ContextSocket>().unwrap(); + let size = socket.window().logical_size(); + Ok((size.width, size.height)) +} + +pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult { + 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(()) +} diff --git a/src/app.rs b/src/app.rs index b932dbf..0a574c6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -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) { + self.input + .set_mouse_pos(pos.to_logical(self.window.scale_factor)); + } +} pub struct App { gfx_context: Option, - lua_instance: LuaInstance, + state: AppState, + tessellator: Tessellator, + force_render: bool, + current_mode: AppMode, } impl App { pub fn new() -> Result { - 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 { + 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 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 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 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 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); } _ => {} } diff --git a/src/context.rs b/src/context.rs deleted file mode 100644 index 9ae2796..0000000 --- a/src/context.rs +++ /dev/null @@ -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 = RefCell::new(Context::new()); -} - -pub struct Context { - window: Option>, - screen_size: PhysicalSize, - 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 { - self.screen_size.to_logical(self.pixels_per_point) - } - - pub fn mouse_pos_logical(&self) -> LogicalPoint { - 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) { - 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, - 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) { - 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, - rect: LogicalRect, - 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, - quad: LogicalQuad, - 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, - 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) -> usize { - let layout = self.fonts.layout(job, self.pixels_per_point as f32); - layout.cursor_index(cursor) - } -} diff --git a/src/fonts.rs b/src/fonts.rs index 864848c..7c3ca5e 100644 --- a/src/fonts.rs +++ b/src/fonts.rs @@ -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, + pixels_per_point: f32, + ) -> usize { + let layout = self.layout(job, pixels_per_point); + layout.cursor_index(cursor) + } } struct CachedLayout { diff --git a/src/gfx.rs b/src/gfx.rs index 4ff07e8..0adfae3 100644 --- a/src/gfx.rs +++ b/src/gfx.rs @@ -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, + textures_delta: TexturesDelta, + }, + Skip, +} + pub struct GraphicsContext { surface: wgpu::Surface<'static>, device: wgpu::Device, diff --git a/src/input.rs b/src/input.rs index fd2b1e9..4f5a537 100644 --- a/src/input.rs +++ b/src/input.rs @@ -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, mouse_pressed: HashSet, mouse_last_pressed: HashMap, - cursor_pos: PhysicalPoint, + cursor_pos: LogicalPoint, } 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 { - 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 { + self.cursor_pos + } + + pub fn set_mouse_pos(&mut self, pos: LogicalPoint) { + self.cursor_pos = pos; + } } pub fn str_as_keycode(s: &str) -> Option { @@ -169,104 +149,101 @@ pub fn str_as_keycode(s: &str) -> Option { }) } -pub fn keycode_as_str(code: KeyCode) -> Option { - 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 { @@ -280,16 +257,13 @@ pub fn str_as_mousebutton(s: &str) -> Option { }) } -pub fn mousebutton_as_str(button: MouseButton) -> Option { - 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, + }) } diff --git a/src/installer.rs b/src/installer.rs index 651d8f0..b9bc9b0 100644 --- a/src/installer.rs +++ b/src/installer.rs @@ -1,31 +1,168 @@ -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 std::{ fs::{self}, io::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(); - - // run installer iff Launch.lua doesn't exist, meaning this is likely the first run - if script_dir.join("Launch.lua").exists() { - return Ok(()); - } - - download_path_of_building(script_dir.as_path())?; - replace_manifest(script_dir.as_path())?; - - Ok(()) +enum DownloadProgress { + Percentage(f32), + TotalBytes(u64), } -/// Download latest release of Path of Building -fn download_path_of_building>(target_dir: P) -> anyhow::Result<()> { - println!("Downloading latest release of Path of Building..."); +enum Progress { + Download(DownloadProgress), // download progress as a percentage (between 0 and 1) + 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>, + 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 || { + // Launch already exists meaning assets have already been downloaded + if script_dir.join("Launch.lua").exists() { + progress_tx.send(Progress::Complete).unwrap(); + return; + } + + if let Err(err) = download_path_of_building(script_dir.as_path(), &progress_tx) { + progress_tx.send(Progress::Error(err)).unwrap(); + } + + replace_manifest(script_dir.as_path()).unwrap(); + 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 { + 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> { + 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> { + 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::(); + 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()) + } +} + +/// Downloads latest release of Path of Building +fn download_path_of_building>( + target_dir: P, + progress_tx: &mpsc::Sender, +) -> anyhow::Result<()> { + log::info!("Downloading Path of Building assets..."); let repo = match Game::current() { Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding", @@ -37,9 +174,14 @@ fn download_path_of_building>(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::().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,6 +227,15 @@ fn download_path_of_building>(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(()) @@ -93,7 +244,7 @@ fn download_path_of_building>(target_dir: P) -> anyhow::Result<() /// 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>(target_dir: P) -> anyhow::Result<()> { - log::info!("Replacing manifest..."); + log::info!("Downloading modified manifest..."); let game_path = match Game::current() { Game::Poe1 => "poe1", @@ -132,3 +283,19 @@ fn download_file>(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) + } +} diff --git a/src/layers.rs b/src/layers.rs index 3cc2eab..3a3f871 100644 --- a/src/layers.rs +++ b/src/layers.rs @@ -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>, current_layer: (i32, i32), viewport: LogicalRect, + 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 { + pub fn consume_layers(&mut self) -> Box> { 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) { self.viewport = viewport; } + pub fn set_viewport_from_size(&mut self, size: LogicalSize) { + 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, + rect: LogicalRect, + 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, + quad: LogicalQuad, + 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, + layout: std::sync::Arc, + 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 { diff --git a/src/lua.rs b/src/lua.rs index 9f027e4..07d30d0 100644 --- a/src/lua.rs +++ b/src/lua.rs @@ -1,16 +1,154 @@ -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>, +} + +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()), + })) + } + + 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); + } + + 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()); + } + + 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); +} + +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>, @@ -23,14 +161,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 { @@ -42,90 +176,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")?; diff --git a/src/main.rs b/src/main.rs index 73e8987..f8bc11b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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()?; diff --git a/src/mode.rs b/src/mode.rs new file mode 100644 index 0000000..6c4eb68 --- /dev/null +++ b/src/mode.rs @@ -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>, + pub can_elide: bool, +} + +pub enum AppMode { + Install(InstallMode), + PoB(PoBMode), +} + +impl AppMode { + pub fn frame(&mut self, state: &mut AppState) -> anyhow::Result { + match self { + AppMode::Install(mode) => mode.frame(state), + AppMode::PoB(mode) => mode.frame(state), + } + } + + pub fn update(&mut self, state: &mut AppState) -> anyhow::Result> { + 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), + } + } +} diff --git a/src/pob.rs b/src/pob.rs new file mode 100644 index 0000000..66a9ef8 --- /dev/null +++ b/src/pob.rs @@ -0,0 +1,143 @@ +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, +} + +/// 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 { + let mut state = PoBState { + layers: Layers::default(), + current_working_dir: PathBuf::default(), + needs_restart: 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 { + 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> { + 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) { + self.state + .layers + .set_viewport(LogicalRect::from_size(size).cast()); + } +} diff --git a/src/window.rs b/src/window.rs new file mode 100644 index 0000000..25d2094 --- /dev/null +++ b/src/window.rs @@ -0,0 +1,45 @@ +use std::sync::Arc; + +use winit::window::Window; + +use crate::dpi::{ConvertToLogical, LogicalSize, PhysicalSize}; + +pub struct WindowState { + pub window: Option>, + pub size: PhysicalSize, + pub scale_factor: f32, + pending_window_title: std::cell::Cell>, +} + +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) { + 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 { + self.size.to_logical(self.scale_factor) + } +}