From 895da317e842154ef625a674ea15f51e061414ad Mon Sep 17 00:00:00 2001 From: griffi-gh Date: Sat, 17 Feb 2024 23:14:04 +0100 Subject: [PATCH] separate `kubi-ui` as `hui` --- Cargo.lock | 63 ++--- Cargo.toml | 8 +- README.md | 2 +- kubi-ui-examples/Cargo.toml | 16 -- kubi-ui-examples/examples/mom_downloader.rs | 111 -------- kubi-ui-examples/examples/stress.rs | 90 ------- kubi-ui-examples/examples/test.rs | 146 ----------- kubi-ui-examples/examples/text_weird.rs | 116 --------- kubi-ui-glium/Cargo.toml | 12 - kubi-ui-glium/shaders/fragment.frag | 12 - kubi-ui-glium/shaders/fragment_tex.frag | 13 - kubi-ui-glium/shaders/vertex.vert | 17 -- kubi-ui-glium/src/lib.rs | 229 ----------------- kubi-ui/Cargo.toml | 19 -- kubi-ui/assets/font/Licence.txt | 7 - kubi-ui/assets/font/ProggyTiny.ttf | Bin 35656 -> 0 bytes kubi-ui/src/draw.rs | 220 ---------------- kubi-ui/src/element.rs | 29 --- kubi-ui/src/element/builtin/container.rs | 237 ------------------ kubi-ui/src/element/builtin/progress_bar.rs | 70 ------ kubi-ui/src/element/builtin/rect.rs | 54 ---- kubi-ui/src/element/builtin/spacer.rs | 32 --- kubi-ui/src/element/builtin/text.rs | 61 ----- kubi-ui/src/event.rs | 10 - kubi-ui/src/interaction.rs | 51 ---- kubi-ui/src/lib.rs | 129 ---------- kubi-ui/src/measure.rs | 15 -- kubi-ui/src/state.rs | 9 - kubi-ui/src/text.rs | 50 ---- kubi-ui/src/text/font.rs | 44 ---- kubi-ui/src/text/ftm.rs | 139 ---------- kubi/Cargo.toml | 4 +- ...i_ui_integration.rs => hui_integration.rs} | 86 +++---- kubi/src/lib.rs | 4 +- kubi/src/loading_screen.rs | 120 ++++----- 35 files changed, 138 insertions(+), 2087 deletions(-) delete mode 100644 kubi-ui-examples/Cargo.toml delete mode 100644 kubi-ui-examples/examples/mom_downloader.rs delete mode 100644 kubi-ui-examples/examples/stress.rs delete mode 100644 kubi-ui-examples/examples/test.rs delete mode 100644 kubi-ui-examples/examples/text_weird.rs delete mode 100644 kubi-ui-glium/Cargo.toml delete mode 100644 kubi-ui-glium/shaders/fragment.frag delete mode 100644 kubi-ui-glium/shaders/fragment_tex.frag delete mode 100644 kubi-ui-glium/shaders/vertex.vert delete mode 100644 kubi-ui-glium/src/lib.rs delete mode 100644 kubi-ui/Cargo.toml delete mode 100644 kubi-ui/assets/font/Licence.txt delete mode 100644 kubi-ui/assets/font/ProggyTiny.ttf delete mode 100644 kubi-ui/src/draw.rs delete mode 100644 kubi-ui/src/element.rs delete mode 100644 kubi-ui/src/element/builtin/container.rs delete mode 100644 kubi-ui/src/element/builtin/progress_bar.rs delete mode 100644 kubi-ui/src/element/builtin/rect.rs delete mode 100644 kubi-ui/src/element/builtin/spacer.rs delete mode 100644 kubi-ui/src/element/builtin/text.rs delete mode 100644 kubi-ui/src/event.rs delete mode 100644 kubi-ui/src/interaction.rs delete mode 100644 kubi-ui/src/lib.rs delete mode 100644 kubi-ui/src/measure.rs delete mode 100644 kubi-ui/src/state.rs delete mode 100644 kubi-ui/src/text.rs delete mode 100644 kubi-ui/src/text/font.rs delete mode 100644 kubi-ui/src/text/ftm.rs rename kubi/src/{kubi_ui_integration.rs => hui_integration.rs} (77%) diff --git a/Cargo.lock b/Cargo.lock index e872cb2..707086b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -886,6 +886,30 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hui" +version = "0.0.2" +source = "git+https://github.com/griffi-gh/hui?rev=1e1dccde0c#1e1dccde0c1f8ba8f4143a5a57d91cf923203508" +dependencies = [ + "fontdue", + "glam", + "hashbrown 0.14.3", + "log", + "nohash-hasher", + "rect_packer", +] + +[[package]] +name = "hui-glium" +version = "0.0.2" +source = "git+https://github.com/griffi-gh/hui?rev=1e1dccde0c#1e1dccde0c1f8ba8f4143a5a57d91cf923203508" +dependencies = [ + "glam", + "glium", + "hui", + "log", +] + [[package]] name = "humantime" version = "2.1.0" @@ -1073,11 +1097,11 @@ dependencies = [ "glutin", "glutin-winit", "hashbrown 0.14.3", + "hui", + "hui-glium", "image", "kubi-logging", "kubi-shared", - "kubi-ui", - "kubi-ui-glium", "log", "lz4_flex", "ndk", @@ -1152,41 +1176,6 @@ dependencies = [ "strum", ] -[[package]] -name = "kubi-ui" -version = "0.0.0" -dependencies = [ - "fontdue", - "glam", - "hashbrown 0.14.3", - "log", - "nohash-hasher", - "rect_packer", -] - -[[package]] -name = "kubi-ui-examples" -version = "0.0.0" -dependencies = [ - "glam", - "glium", - "kubi-logging", - "kubi-ui", - "kubi-ui-glium", - "log", - "winit", -] - -[[package]] -name = "kubi-ui-glium" -version = "0.0.0" -dependencies = [ - "glam", - "glium", - "kubi-ui", - "log", -] - [[package]] name = "lazy_static" version = "1.4.0" diff --git a/Cargo.toml b/Cargo.toml index e15ab38..caa0c27 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,10 +4,7 @@ members = [ "kubi-server", "kubi-shared", "kubi-logging", - "kubi-pool", - "kubi-ui", - "kubi-ui-glium", - "kubi-ui-examples" + "kubi-pool" ] default-members = ["kubi"] resolver = "2" @@ -38,3 +35,6 @@ opt-level = 3 #enabling debug assertions here causes the game to abort [profile.dev.package.android-activity] debug-assertions = false + +[patch.crates-io] +glium = { git = "https://github.com/glium/glium", rev = "a352c667" } diff --git a/README.md b/README.md index c055bae..add1ce3 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ name = "Kubi Server" # server name

"In-house" libraries

-- [`kubi-ui`](kubi-ui): semi-imm.mode backend-agnostic ui system\ +- [`hui`](https://github.com/griffi-gh/hui): semi-imm.mode backend-agnostic ui system\ mostly ready to use, it has already replaced the Kubi legacy ui - [`kubi-ui-glium`](kubi-ui-glium) Glium-based backend for `kubi-ui` - [`kubi-pool`](kubi-pool): very early work-in-progress work-stealing threadpool system\ diff --git a/kubi-ui-examples/Cargo.toml b/kubi-ui-examples/Cargo.toml deleted file mode 100644 index d191eeb..0000000 --- a/kubi-ui-examples/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -#created as a workaround for rust-analyzer dependency cycle (which should be allowed) - -[package] -name = "kubi-ui-examples" -version = "0.0.0" -edition = "2021" -publish = false - -[dev-dependencies] -kubi-ui = { path = "../kubi-ui" } -kubi-ui-glium = { path = "../kubi-ui-glium" } -kubi-logging = { path = "../kubi-logging" } -glium = { git = "https://github.com/glium/glium", rev = "a352c667" } -winit = "0.29" -glam = "0.25" -log = "0.4" diff --git a/kubi-ui-examples/examples/mom_downloader.rs b/kubi-ui-examples/examples/mom_downloader.rs deleted file mode 100644 index 2d6dcc6..0000000 --- a/kubi-ui-examples/examples/mom_downloader.rs +++ /dev/null @@ -1,111 +0,0 @@ -use std::time::Instant; -use glam::{UVec2, vec4}; -use glium::{backend::glutin::SimpleWindowBuilder, Surface}; -use winit::{ - event::{Event, WindowEvent}, - event_loop::{EventLoopBuilder, ControlFlow} -}; -use kubi_ui::{ - KubiUi, - element::{ - progress_bar::ProgressBar, - container::{Container, Sides, Alignment}, - text::Text - }, - UiSize, - elements, -}; -use kubi_ui_glium::GliumUiRenderer; - -fn main() { - kubi_logging::init(); - - let event_loop = EventLoopBuilder::new().build().unwrap(); - let (window, display) = SimpleWindowBuilder::new().build(&event_loop); - window.set_title("Mom Downloader 2000"); - - let mut kui = KubiUi::new(); - let mut backend = GliumUiRenderer::new(&display); - - let font_handle = kui.add_font_from_bytes(include_bytes!("../../assets/fonts/roboto/Roboto-Regular.ttf")); - - let instant = Instant::now(); - - event_loop.run(|event, window_target| { - window_target.set_control_flow(ControlFlow::Poll); - match event { - Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { - window_target.exit(); - }, - Event::AboutToWait => { - let mut frame = display.draw(); - frame.clear_color_srgb(0., 0., 0., 1.); - - let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2(); - - kui.begin(); - - let mom_ratio = (instant.elapsed().as_secs_f32() / 60.).powf(0.5); - - kui.add(Container { - align: (Alignment::Center, Alignment::Center), - size: (UiSize::Percentage(1.), UiSize::Percentage(1.)), - background: Some(vec4(0.1, 0.1, 0.1, 1.)), - elements: vec![Box::new(Container { - gap: 5., - padding: Sides::all(10.), - align: (Alignment::Begin, Alignment::Begin), - size: (UiSize::Pixels(450.), UiSize::Auto), - background: Some(vec4(0.2, 0.2, 0.5, 1.)), - elements: elements(|el| { - if instant.elapsed().as_secs_f32() < 5. { - el.add(Text { - text: "Downloading your mom...".into(), - font: font_handle, - text_size: 32, - ..Default::default() - }); - el.add(ProgressBar { - value: mom_ratio, - ..Default::default() - }); - el.add(Text { - text: format!("{:.2}% ({:.1} GB)", mom_ratio * 100., mom_ratio * 10000.).into(), - font: font_handle, - text_size: 24, - ..Default::default() - }); - } else if instant.elapsed().as_secs() < 10 { - el.add(Text { - text: "Error 413 Request Entity Too Large".into(), - font: font_handle, - color: vec4(1., 0.125, 0.125, 1.), - text_size: 26, - ..Default::default() - }); - el.add(Text { - text: format!("Exiting in {}...", 10 - instant.elapsed().as_secs()).into(), - font: font_handle, - text_size: 24, - ..Default::default() - }) - } else { - window_target.exit(); - } - }), - ..Default::default() - })], - ..Default::default() - }, resolution); - - kui.end(); - - backend.update(&kui); - backend.draw(&mut frame, resolution); - - frame.finish().unwrap(); - } - _ => (), - } - }).unwrap(); -} diff --git a/kubi-ui-examples/examples/stress.rs b/kubi-ui-examples/examples/stress.rs deleted file mode 100644 index 52a1843..0000000 --- a/kubi-ui-examples/examples/stress.rs +++ /dev/null @@ -1,90 +0,0 @@ -use std::time::Instant; -use glam::{Vec2, IVec2, UVec2}; -use glium::{backend::glutin::SimpleWindowBuilder, Surface}; -use winit::{ - event::{Event, WindowEvent}, - event_loop::{EventLoopBuilder, ControlFlow} -}; -use kubi_ui::{ - KubiUi, - element::{ - UiElement, - progress_bar::ProgressBar, - container::{Container, Sides} - }, - UiSize -}; -use kubi_ui_glium::GliumUiRenderer; - -fn main() { - kubi_logging::init(); - - let event_loop = EventLoopBuilder::new().build().unwrap(); - let (window, display) = SimpleWindowBuilder::new().build(&event_loop); - - let mut kui = KubiUi::new(); - let mut backend = GliumUiRenderer::new(&display); - - let instant = Instant::now(); - let mut pcnt = 0; - event_loop.run(|event, window_target| { - window_target.set_control_flow(ControlFlow::Poll); - match event { - Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { - window_target.exit(); - }, - Event::AboutToWait => { - let mut frame = display.draw(); - frame.clear_color_srgb(0.5, 0.5, 0.5, 0.); - - let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2(); - - kui.begin(); - - kui.add(Container { - gap: 5., - padding: Sides::all(5.), - elements: vec![ - Box::new(ProgressBar { - value: 0.5, - ..Default::default() - }), - Box::new(ProgressBar { - value: instant.elapsed().as_secs_f32().sin().powi(2), - ..Default::default() - }), - Box::new(Container { - gap: 1., - elements: { - let mut elements: Vec> = vec![]; - let cnt = instant.elapsed().as_secs() * 10000; - if pcnt != cnt { - log::info!("{cnt}"); - pcnt = cnt; - } - for i in 0..cnt { - elements.push(Box::new(ProgressBar { - value: (instant.elapsed().as_secs_f32() + (i as f32 / 10.)).sin().powi(2), - size: (UiSize::Auto, UiSize::Pixels(5.)), - ..Default::default() - })); - } - elements - }, - ..Default::default() - }) - ], - ..Default::default() - }, resolution); - - kui.end(); - - backend.update(&kui); - backend.draw(&mut frame, resolution); - - frame.finish().unwrap(); - } - _ => (), - } - }).unwrap(); -} diff --git a/kubi-ui-examples/examples/test.rs b/kubi-ui-examples/examples/test.rs deleted file mode 100644 index 8a289e7..0000000 --- a/kubi-ui-examples/examples/test.rs +++ /dev/null @@ -1,146 +0,0 @@ -use std::time::Instant; -use glam::{UVec2, vec4}; -use glium::{backend::glutin::SimpleWindowBuilder, Surface}; -use winit::{ - event::{Event, WindowEvent}, - event_loop::{EventLoopBuilder, ControlFlow} -}; -use kubi_ui::{ - KubiUi, - element::{ - UiElement, - progress_bar::ProgressBar, - container::{Container, Sides, Alignment}, - rect::Rect - }, - interaction::IntoInteractable, - UiSize, - UiDirection, IfModified, -}; -use kubi_ui_glium::GliumUiRenderer; - -fn main() { - kubi_logging::init(); - - let event_loop = EventLoopBuilder::new().build().unwrap(); - let (window, display) = SimpleWindowBuilder::new().build(&event_loop); - - let mut kui = KubiUi::new(); - let mut backend = GliumUiRenderer::new(&display); - - let instant = Instant::now(); - event_loop.run(|event, window_target| { - window_target.set_control_flow(ControlFlow::Poll); - match event { - Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { - window_target.exit(); - }, - Event::AboutToWait => { - let mut frame = display.draw(); - frame.clear_color_srgb(0.5, 0.5, 0.5, 0.); - - let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2(); - - kui.begin(); - - let z = instant.elapsed().as_secs_f32().sin().powi(2); - - kui.add(Container { - gap: 5., - padding: Sides::all(5.), - align: (Alignment::Begin, Alignment::Center), - size: (UiSize::Percentage(1.), UiSize::Percentage(1.)), - elements: vec![ - Box::new(ProgressBar { - value: 0.5, - ..Default::default() - }), - ], - ..Default::default() - }, resolution); - - kui.add(Container { - gap: 5., - padding: Sides::all(5.), - align: (Alignment::End, Alignment::Center), - size: (UiSize::Percentage(1.), UiSize::Percentage(1.)), - elements: vec![ - Box::new(ProgressBar { - value: z, - ..Default::default() - }), - Box::new(Container { - size: (UiSize::Percentage(1.), UiSize::Auto), - align: (Alignment::Center, Alignment::End), - padding: Sides::all(5.), - gap: 10., - elements: vec![ - Box::new(Rect { - size: (UiSize::Percentage(0.5), UiSize::Pixels(30.)), - color: Some(vec4(0.75, 0., 0., 1.)) - }), - Box::new(Rect { - size: (UiSize::Percentage(z / 2. + 0.5), UiSize::Pixels(30.)), - color: Some(vec4(0., 0.75, 0., 1.)) - }), - ], - ..Default::default() - }), - Box::new(Rect { - size: (UiSize::Percentage(z / 2. + 0.5), UiSize::Pixels(30.)), - color: Some(vec4(0., 0.75, 0., 1.)) - }), - Box::new(Container { - gap: 5., - padding: Sides::all(5.), - background: Some(vec4(0., 0., 0., 0.5)), - direction: UiDirection::Horizontal, - elements: { - let mut x: Vec> = vec![]; - for i in 0..10 { - x.push(Box::new(Rect { - size: (UiSize::Pixels(50.), UiSize::Pixels(50.)), - color: if i == 1 { - Some(vec4(0.75, 0.75, 0.75, 0.75)) - } else { - Some(vec4(0.5, 0.5, 0.5, 0.75)) - } - })); - } - x - }, - ..Default::default() - }), - Box::new(Container { - background: Some(vec4(1., 0., 0., 1.)), - padding: Sides { - top: 10., - bottom: 20., - left: 30., - right: 40., - }, - elements: vec![ - Box::new(Rect { - size: (UiSize::Pixels(50.), UiSize::Pixels(50.)), - color: Some(vec4(1., 1., 1., 0.75)) - }.into_interactable().on_click(|| { - println!("clicked"); - })) - ], - ..Default::default() - }) - ], - ..Default::default() - }, resolution); - - kui.end(); - - backend.update(&kui); - backend.draw(&mut frame, resolution); - - frame.finish().unwrap(); - } - _ => (), - } - }).unwrap(); -} diff --git a/kubi-ui-examples/examples/text_weird.rs b/kubi-ui-examples/examples/text_weird.rs deleted file mode 100644 index 2c64884..0000000 --- a/kubi-ui-examples/examples/text_weird.rs +++ /dev/null @@ -1,116 +0,0 @@ -use std::{time::Instant, vec}; -use glam::{UVec2, vec4}; -use glium::{backend::glutin::SimpleWindowBuilder, Surface}; -use winit::{ - event::{Event, WindowEvent}, - event_loop::{EventLoopBuilder, ControlFlow} -}; -use kubi_ui::{ - KubiUi, - element::{ - progress_bar::ProgressBar, - container::{Container, Sides, Alignment}, - text::Text, rect::Rect, spacer::Spacer - }, - UiSize, - elements, -}; -use kubi_ui_glium::GliumUiRenderer; - -fn main() { - kubi_logging::init(); - - let event_loop = EventLoopBuilder::new().build().unwrap(); - let (window, display) = SimpleWindowBuilder::new().build(&event_loop); - window.set_title("Text rendering test"); - - let mut kui = KubiUi::new(); - let mut backend = GliumUiRenderer::new(&display); - - let font_handle = kui.add_font_from_bytes(include_bytes!("../../assets/fonts/roboto/Roboto-Regular.ttf")); - let instant = Instant::now(); - - event_loop.run(|event, window_target| { - window_target.set_control_flow(ControlFlow::Poll); - match event { - Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => { - window_target.exit(); - }, - Event::AboutToWait => { - let mut frame = display.draw(); - frame.clear_color_srgb(0., 0., 0., 1.); - - let resolution = UVec2::from(display.get_framebuffer_dimensions()).as_vec2(); - - kui.begin(); - - kui.add(Container { - size: (UiSize::Percentage(1.), UiSize::Percentage(1.)), - background: Some(vec4(0.1, 0.1, 0.1, 1.)), - elements: elements(|elem| { - elem.add(Text { - text: "THIS LINE SHOULD BE SHARP!".into(), - ..Default::default() - }); - elem.add(Text { - text: "THIS LINE SHOULD BE SHARP!".into(), - text_size: 32, - ..Default::default() - }); - elem.add(Text { - text: "All lines except 3 and 6 below will be blurry:".into(), - ..Default::default() - }); - for size in [9, 12, 16, 18, 24, 32] { - elem.add(Text { - text: "Testing default font, Proggy Tiny".into(), - text_size: size, - ..Default::default() - }); - } - elem.add(Rect { - size: (UiSize::Percentage(1.), UiSize::Pixels(10.)), - color: Some(vec4(0., 0., 1., 1.)), - }); - elem.add(Rect { - size: (UiSize::Percentage(1.), UiSize::Pixels(10.)), - color: Some(vec4(1., 1., 0., 1.)), - }); - elem.add(Text { - text: "Hello, world!\nżółty liść. życie nie ma sensu i wszyscy zginemy;\nтест кирилиці їїїїїїїїїїї\njapanese text: テスト".into(), - font: font_handle, - text_size: 32, - ..Default::default() - }); - if instant.elapsed().as_secs() & 1 != 0 { - elem.add(Rect { - size: (UiSize::Percentage(1.), UiSize::Pixels(10.)), - color: Some(vec4(1., 0., 0., 1.)), - }); - elem.add(Rect { - size: (UiSize::Percentage(1.), UiSize::Pixels(10.)), - color: Some(vec4(0., 0., 0., 1.)), - }); - elem.add(Spacer(100.)); - elem.add(Text { - text: "FLAG SHOULD NOT OVERLAP WITH TEXT".into(), - text_size: 64, - color: vec4(1., 0., 1., 1.), - ..Default::default() - }); - } - }), - ..Default::default() - }, resolution); - - kui.end(); - - backend.update(&kui); - backend.draw(&mut frame, resolution); - - frame.finish().unwrap(); - } - _ => (), - } - }).unwrap(); -} diff --git a/kubi-ui-glium/Cargo.toml b/kubi-ui-glium/Cargo.toml deleted file mode 100644 index d4375de..0000000 --- a/kubi-ui-glium/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "kubi-ui-glium" -version = "0.0.0" -edition = "2021" -publish = false - -[dependencies] -kubi-ui = { path = "../kubi-ui", default-features = false } -#kubi-ui = { path = "../kubi-ui" } -glium = { git = "https://github.com/glium/glium", rev = "a352c667" } -glam = "0.25" -log = "0.4" diff --git a/kubi-ui-glium/shaders/fragment.frag b/kubi-ui-glium/shaders/fragment.frag deleted file mode 100644 index 2f60ee9..0000000 --- a/kubi-ui-glium/shaders/fragment.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 300 es - -precision highp float; -precision highp sampler2D; - -out vec4 out_color; -in vec4 vtx_color; -in vec2 vtx_uv; - -void main() { - out_color = vtx_color; -} diff --git a/kubi-ui-glium/shaders/fragment_tex.frag b/kubi-ui-glium/shaders/fragment_tex.frag deleted file mode 100644 index d4c5b82..0000000 --- a/kubi-ui-glium/shaders/fragment_tex.frag +++ /dev/null @@ -1,13 +0,0 @@ -#version 300 es - -precision highp float; -precision highp sampler2D; - -out vec4 out_color; -in vec4 vtx_color; -in vec2 vtx_uv; -uniform sampler2D tex; - -void main() { - out_color = texture(tex, vtx_uv) * vtx_color; -} diff --git a/kubi-ui-glium/shaders/vertex.vert b/kubi-ui-glium/shaders/vertex.vert deleted file mode 100644 index 6df175f..0000000 --- a/kubi-ui-glium/shaders/vertex.vert +++ /dev/null @@ -1,17 +0,0 @@ -#version 300 es - -precision highp float; - -uniform vec2 resolution; -in vec2 uv; -in vec4 color; -in vec2 position; -out vec4 vtx_color; -out vec2 vtx_uv; - -void main() { - vtx_color = color; - vtx_uv = uv; - vec2 pos2d = (vec2(2., -2.) * (position / resolution)) + vec2(-1, 1); - gl_Position = vec4(pos2d, 0., 1.); -} diff --git a/kubi-ui-glium/src/lib.rs b/kubi-ui-glium/src/lib.rs deleted file mode 100644 index 39d647e..0000000 --- a/kubi-ui-glium/src/lib.rs +++ /dev/null @@ -1,229 +0,0 @@ -use std::rc::Rc; -use glam::Vec2; -use glium::{ - Surface, DrawParameters, Blend, - Program, VertexBuffer, IndexBuffer, - backend::{Facade, Context}, - texture::{SrgbTexture2d, RawImage2d}, - index::PrimitiveType, - implement_vertex, - uniform, uniforms::{Sampler, SamplerBehavior, SamplerWrapFunction}, -}; -use kubi_ui::{ - KubiUi, - draw::{UiDrawPlan, UiVertex, BindTexture}, - text::FontTextureInfo, IfModified, -}; - -const VERTEX_SHADER: &str = include_str!("../shaders/vertex.vert"); -const FRAGMENT_SHADER: &str = include_str!("../shaders/fragment.frag"); -const FRAGMENT_SHADER_TEX: &str = include_str!("../shaders/fragment_tex.frag"); - -#[derive(Clone, Copy)] -#[repr(C)] -struct Vertex { - position: [f32; 2], - color: [f32; 4], - uv: [f32; 2], -} - -impl From for Vertex { - fn from(v: UiVertex) -> Self { - Self { - position: v.position.to_array(), - color: v.color.to_array(), - uv: v.uv.to_array(), - } - } -} - -implement_vertex!(Vertex, position, color, uv); - -struct BufferPair { - pub vertex_buffer: glium::VertexBuffer, - pub index_buffer: glium::IndexBuffer, - pub vertex_count: usize, - pub index_count: usize, -} - -impl BufferPair { - pub fn new(facade: &F) -> Self { - log::debug!("init ui buffers..."); - Self { - vertex_buffer: VertexBuffer::empty_dynamic(facade, 1024).unwrap(), - index_buffer: IndexBuffer::empty_dynamic(facade, PrimitiveType::TrianglesList, 1024).unwrap(), - vertex_count: 0, - index_count: 0, - } - } - - pub fn ensure_buffer_size(&mut self, need_vtx: usize, need_idx: usize) { - let current_vtx_size = self.vertex_buffer.get_size() / std::mem::size_of::(); - let current_idx_size = self.index_buffer.get_size() / std::mem::size_of::(); - //log::debug!("current vtx size: {}, current idx size: {}", current_vtx_size, current_idx_size); - if current_vtx_size >= need_vtx && current_idx_size >= need_idx { - return - } - let new_vtx_size = (need_vtx + 1).next_power_of_two(); - let new_idx_size = (need_idx + 1).next_power_of_two(); - log::debug!("resizing buffers: vtx {} -> {}, idx {} -> {}", current_vtx_size, new_vtx_size, current_idx_size, new_idx_size); - if current_vtx_size != new_vtx_size { - self.vertex_buffer = VertexBuffer::empty_dynamic( - self.vertex_buffer.get_context(), - new_vtx_size - ).unwrap(); - } - if current_idx_size != new_idx_size { - self.index_buffer = IndexBuffer::empty_dynamic( - self.index_buffer.get_context(), - PrimitiveType::TrianglesList, - new_idx_size - ).unwrap(); - } - } - - pub fn write_data(&mut self, vtx: &[Vertex], idx: &[u32]) { - //log::trace!("uploading {} vertices and {} indices", vtx.len(), idx.len()); - - self.vertex_count = vtx.len(); - self.index_count = idx.len(); - - self.vertex_buffer.invalidate(); - self.index_buffer.invalidate(); - - if self.vertex_count == 0 || self.index_count == 0 { - return - } - - self.ensure_buffer_size(self.vertex_count, self.index_count); - - self.vertex_buffer.slice_mut(0..self.vertex_count).unwrap().write(vtx); - self.index_buffer.slice_mut(0..self.index_count).unwrap().write(idx); - } - - pub fn is_empty(&self) -> bool { - self.vertex_count == 0 || self.index_count == 0 - } -} - -struct GlDrawCall { - active: bool, - buffer: BufferPair, - bind_texture: Option>, -} - -pub struct GliumUiRenderer { - context: Rc, - program: glium::Program, - program_tex: glium::Program, - font_texture: Option>, - plan: Vec, -} - -impl GliumUiRenderer { - pub fn new(facade: &F) -> Self { - log::info!("init glium backend for kui"); - Self { - program: Program::from_source(facade, VERTEX_SHADER, FRAGMENT_SHADER, None).unwrap(), - program_tex: Program::from_source(facade, VERTEX_SHADER, FRAGMENT_SHADER_TEX, None).unwrap(), - context: Rc::clone(facade.get_context()), - font_texture: None, - plan: vec![] - } - } - - pub fn update_draw_plan(&mut self, plan: &UiDrawPlan) { - if plan.calls.len() > self.plan.len() { - self.plan.resize_with(plan.calls.len(), || { - GlDrawCall { - buffer: BufferPair::new(&self.context), - bind_texture: None, - active: false, - } - }); - } else { - for step in &mut self.plan[plan.calls.len()..] { - step.active = false; - } - } - for (idx, call) in plan.calls.iter().enumerate() { - let data_vtx = &call.vertices.iter().copied().map(Vertex::from).collect::>()[..]; - let data_idx = &call.indices[..]; - self.plan[idx].active = true; - self.plan[idx].buffer.write_data(data_vtx, data_idx); - self.plan[idx].bind_texture = match call.bind_texture { - Some(BindTexture::FontTexture) => { - const NO_FNT_TEX: &str = "Font texture exists in draw plan but not yet inited. Make sure to call update_font_texture() *before* update_draw_plan()"; - Some(Rc::clone(self.font_texture.as_ref().expect(NO_FNT_TEX))) - }, - None => None, - } - } - } - - pub fn update_font_texture(&mut self, font_texture: &FontTextureInfo) { - log::debug!("updating font texture"); - self.font_texture = Some(Rc::new(SrgbTexture2d::new( - &self.context, - RawImage2d::from_raw_rgba( - font_texture.data.to_owned(), - (font_texture.size.x, font_texture.size.y) - ) - ).unwrap())); - } - - pub fn update(&mut self, kui: &KubiUi) { - if let Some(texture) = kui.font_texture().if_modified() { - self.update_font_texture(texture); - } - if let Some(plan) = kui.draw_plan().if_modified() { - self.update_draw_plan(plan); - } - } - - pub fn draw(&self, frame: &mut glium::Frame, resolution: Vec2) { - let params = DrawParameters { - blend: Blend::alpha_blending(), - ..Default::default() - }; - - for step in &self.plan { - if !step.active { - continue - } - - if step.buffer.is_empty() { - continue - } - - let vtx_buffer = step.buffer.vertex_buffer.slice(0..step.buffer.vertex_count).unwrap(); - let idx_buffer = step.buffer.index_buffer.slice(0..step.buffer.index_count).unwrap(); - - if let Some(bind_texture) = step.bind_texture.as_ref() { - frame.draw( - vtx_buffer, - idx_buffer, - &self.program_tex, - &uniform! { - resolution: resolution.to_array(), - tex: Sampler(bind_texture.as_ref(), SamplerBehavior { - wrap_function: (SamplerWrapFunction::Clamp, SamplerWrapFunction::Clamp, SamplerWrapFunction::Clamp), - ..Default::default() - }), - }, - ¶ms, - ).unwrap(); - } else { - frame.draw( - vtx_buffer, - idx_buffer, - &self.program, - &uniform! { - resolution: resolution.to_array(), - }, - ¶ms, - ).unwrap(); - } - } - } -} diff --git a/kubi-ui/Cargo.toml b/kubi-ui/Cargo.toml deleted file mode 100644 index 887e1e8..0000000 --- a/kubi-ui/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "kubi-ui" -version = "0.0.0" -edition = "2021" -publish = false - -[dependencies] -hashbrown = "0.14" -nohash-hasher = "0.2" -glam = "0.25" -fontdue = "0.8" -rect_packer = "0.2" -log = "0.4" - -[features] -default = ["builtin_elements", "builtin_font"] -builtin_font = [] -builtin_elements = [] -#parallel = ["dep:rayon", "fontdue/parallel"] diff --git a/kubi-ui/assets/font/Licence.txt b/kubi-ui/assets/font/Licence.txt deleted file mode 100644 index ad4a6b6..0000000 --- a/kubi-ui/assets/font/Licence.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2004, 2005 Tristan Grimmer - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/kubi-ui/assets/font/ProggyTiny.ttf b/kubi-ui/assets/font/ProggyTiny.ttf deleted file mode 100644 index 1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8d2lwo` zW82LK?%1|%d~9sf2L9LCOgC|NqqL0<)6H}%9ii=XfXkOkc|Yx^U7Wj?_j~9z+Q&x^ z^SRsTdOqhG&L8CZJ>0@JzWRWq+i=UJ8~#@nrv**S3&68_)rm(nS;jQ`L3QCdN#^8b9lidM5G z*U~yVjZUXCXg%xlEMc=lN=`s3q`e*tl`XZ};2R%SL>0epJ&(Xiozti*dZ}c_#Z`w`Ypcm*r=r35o z->2WBm*_?MCheu~(*MwJ(Z^Wfx3GEaW3_*t&EQw*5SzoTY$QkMcKSHIPDklZHi%!N zU#Gk18Tu3Y1l>(t_RTlwP5RQ@+Ya2knIt+?^CVV`(v!x0A}-N#*UN@^(^rJE^>#RNhW1Zzq+v zlgiskMc2apesl1)tgFAQa+jV5uz$LdGK9~qQkqSGJ3OkVsJCO=IkqSGJ3OkVs zJCO=IkqSGJ3OkVsJCO=IkqSGJ3OkW1cQRG(WGe4uD(_?}?_?_PWGe4uD(_?}?_?_P aWGe4uD(_?}?_?_PWGe4uD(~cOqW=eI(CQrk diff --git a/kubi-ui/src/draw.rs b/kubi-ui/src/draw.rs deleted file mode 100644 index 610916b..0000000 --- a/kubi-ui/src/draw.rs +++ /dev/null @@ -1,220 +0,0 @@ -use crate::{IfModified, text::{TextRenderer, FontHandle}}; - -use std::borrow::Cow; -use fontdue::layout::{Layout, CoordinateSystem, TextStyle}; -use glam::{Vec2, Vec4, vec2}; - -#[derive(Clone, Debug, PartialEq)] -pub enum UiDrawCommand { - ///Filled, colored rectangle - Rectangle { - ///Position in pixels - position: Vec2, - ///Size in pixels - size: Vec2, - ///Color (RGBA) - color: Vec4, - }, - Text { - ///Position in pixels - position: Vec2, - ///Font size - size: u8, - ///Color (RGBA) - color: Vec4, - ///Text to draw - text: Cow<'static, str>, - ///Font handle to use - font: FontHandle, - }, -} - -#[derive(Default)] -pub struct UiDrawCommands { - pub commands: Vec, -} - -impl UiDrawCommands { - pub fn add(&mut self, command: UiDrawCommand) { - self.commands.push(command); - } -} - -// impl UiDrawCommands { -// pub fn compare(&self, other: &Self) -> bool { -// // if self.commands.len() != other.commands.len() { return false } -// // self.commands.iter().zip(other.commands.iter()).all(|(a, b)| a == b) -// } -// } - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BindTexture { - FontTexture, - //UserDefined(usize), -} - -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct UiVertex { - pub position: Vec2, - pub color: Vec4, - pub uv: Vec2, -} - -#[derive(Default)] -pub struct UiDrawCall { - pub vertices: Vec, - pub indices: Vec, - pub bind_texture: Option, -} - -#[derive(Default)] -pub struct UiDrawPlan { - pub calls: Vec -} - -struct CallSwapper { - calls: Vec, - call: UiDrawCall, -} - -impl CallSwapper { - pub fn new() -> Self { - Self { - calls: vec![], - call: UiDrawCall::default(), - } - } - - pub fn current(&self) -> &UiDrawCall { - &self.call - } - - pub fn current_mut(&mut self) -> &mut UiDrawCall { - &mut self.call - } - - pub fn swap(&mut self) { - self.calls.push(std::mem::replace(&mut self.call, UiDrawCall::default())); - } - - pub fn finish(mut self) -> Vec { - self.calls.push(self.call); - self.calls - } -} - -impl UiDrawPlan { - pub fn build(draw_commands: &UiDrawCommands, tr: &mut TextRenderer) -> Self { - let mut swapper = CallSwapper::new(); - let mut prev_command = None; - for command in &draw_commands.commands { - - let do_swap = if let Some(prev_command) = prev_command { - std::mem::discriminant(prev_command) != std::mem::discriminant(command) - } else { - false - }; - - if do_swap { - swapper.swap(); - } - - if do_swap || prev_command.is_none() { - match command { - UiDrawCommand::Rectangle { .. } => (), - UiDrawCommand::Text { .. } => { - swapper.current_mut().bind_texture = Some(BindTexture::FontTexture); - } - } - } - - match command { - UiDrawCommand::Rectangle { position, size, color } => { - let vidx = swapper.current().vertices.len() as u32; - swapper.current_mut().indices.extend([vidx, vidx + 1, vidx + 2, vidx, vidx + 2, vidx + 3]); - swapper.current_mut().vertices.extend([ - UiVertex { - position: *position, - color: *color, - uv: vec2(0.0, 0.0), - }, - UiVertex { - position: *position + vec2(size.x, 0.0), - color: *color, - uv: vec2(1.0, 0.0), - }, - UiVertex { - position: *position + *size, - color: *color, - uv: vec2(1.0, 1.0), - }, - UiVertex { - position: *position + vec2(0.0, size.y), - color: *color, - uv: vec2(0.0, 1.0), - }, - ]); - }, - UiDrawCommand::Text { position, size, color, text, font } => { - //XXX: should we be doing this every time? - let mut layout = Layout::new(CoordinateSystem::PositiveYDown); - layout.append( - &[tr.internal_font(*font)], - &TextStyle::new(text, *size as f32, 0) - ); - let glyphs = layout.glyphs(); - - //let mut rpos_x = 0.; - for layout_glyph in glyphs { - if !layout_glyph.char_data.rasterize() { - continue - } - let vidx = swapper.current().vertices.len() as u32; - let glyph = tr.glyph(*font, layout_glyph.parent, layout_glyph.key.px as u8); - //rpos_x += glyph.metrics.advance_width;//glyph.metrics.advance_width; - swapper.current_mut().indices.extend([vidx, vidx + 1, vidx + 2, vidx, vidx + 2, vidx + 3]); - let p0x = glyph.position.x as f32 / 1024.; - let p1x = (glyph.position.x + glyph.size.x as i32) as f32 / 1024.; - let p0y = glyph.position.y as f32 / 1024.; - let p1y = (glyph.position.y + glyph.size.y as i32) as f32 / 1024.; - swapper.current_mut().vertices.extend([ - UiVertex { - position: *position + vec2(layout_glyph.x, layout_glyph.y), - color: *color, - uv: vec2(p0x, p0y), - }, - UiVertex { - position: *position + vec2(layout_glyph.x + glyph.metrics.width as f32, layout_glyph.y), - color: *color, - uv: vec2(p1x, p0y), - }, - UiVertex { - position: *position + vec2(layout_glyph.x + glyph.metrics.width as f32, layout_glyph.y + glyph.metrics.height as f32), - color: *color, - uv: vec2(p1x, p1y), - }, - UiVertex { - position: *position + vec2(layout_glyph.x, layout_glyph.y + glyph.metrics.height as f32), - color: *color, - uv: vec2(p0x, p1y), - }, - ]); - } - } - } - prev_command = Some(command); - } - Self { - calls: swapper.finish() - } - } -} - -impl IfModified for (bool, &UiDrawPlan) { - fn if_modified(&self) -> Option<&UiDrawPlan> { - match self.0 { - true => Some(self.1), - false => None, - } - } -} diff --git a/kubi-ui/src/element.rs b/kubi-ui/src/element.rs deleted file mode 100644 index 8e5edfa..0000000 --- a/kubi-ui/src/element.rs +++ /dev/null @@ -1,29 +0,0 @@ -use std::any::Any; -use crate::{ - LayoutInfo, - draw::UiDrawCommands, - measure::Response, - state::StateRepo -}; - -#[cfg(feature = "builtin_elements")] -mod builtin { - pub mod rect; - pub mod container; - pub mod spacer; - pub mod progress_bar; - pub mod text; -} - -#[cfg(feature = "builtin_elements")] -pub use builtin::*; - -pub trait UiElement { - fn name(&self) -> &'static str { "UiElement" } - fn state_id(&self) -> Option { None } - fn is_stateful(&self) -> bool { self.state_id().is_some() } - fn is_stateless(&self) -> bool { self.state_id().is_none() } - fn init_state(&self) -> Option> { None } - fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response; - fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands); -} diff --git a/kubi-ui/src/element/builtin/container.rs b/kubi-ui/src/element/builtin/container.rs deleted file mode 100644 index a666425..0000000 --- a/kubi-ui/src/element/builtin/container.rs +++ /dev/null @@ -1,237 +0,0 @@ -use glam::{Vec2, vec2, Vec4}; -use crate::{ - UiDirection, - UiSize, - LayoutInfo, - draw::{UiDrawCommand, UiDrawCommands}, - measure::{Response, Hints}, - state::StateRepo, - element::UiElement -}; - -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum Alignment { - Begin, - Center, - End, -} - -pub struct Border { - pub color: Vec4, - pub width: f32, -} - -#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)] -pub struct Sides { - pub top: T, - pub bottom: T, - pub left: T, - pub right: T, -} - -impl Sides { - #[inline] - pub fn all(value: T) -> Self { - Self { - top: value.clone(), - bottom: value.clone(), - left: value.clone(), - right: value, - } - } - - #[inline] - pub fn horizontal_vertical(horizontal: T, vertical: T) -> Self { - Self { - top: vertical.clone(), - bottom: vertical, - left: horizontal.clone(), - right: horizontal, - } - } -} - -pub struct Container { - // pub min_size: (UiSize, UiSize), - // pub max_size: (UiSize, UiSize), - pub size: (UiSize, UiSize), - pub direction: UiDirection, - //pub reverse: bool, - pub gap: f32, - pub padding: Sides, - ///Primary/secondary axis - pub align: (Alignment, Alignment), - pub background: Option, - pub borders: Sides>, - pub clip: bool, - pub elements: Vec>, -} - -impl Default for Container { - fn default() -> Self { - Self { - // min_size: (UiSize::Auto, UiSize::Auto), - // max_size: (UiSize::Auto, UiSize::Auto), - size: (UiSize::Auto, UiSize::Auto), - direction: UiDirection::Vertical, - //reverse: false, - gap: 0., - padding: Sides::all(0.), - align: (Alignment::Begin, Alignment::Begin), - background: Default::default(), - borders: Default::default(), - clip: Default::default(), - elements: Vec::new(), - } - } -} - -impl Container { - pub fn measure_max_inner_size(&self, layout: &LayoutInfo) -> Vec2 { - let outer_size_x = match self.size.0 { - UiSize::Auto => layout.max_size.x, - UiSize::Percentage(p) => layout.max_size.x * p, - UiSize::Pixels(p) => p, - }; - let outer_size_y = match self.size.1 { - UiSize::Auto => layout.max_size.y, - UiSize::Percentage(p) => layout.max_size.y * p, - UiSize::Pixels(p) => p, - }; - vec2( - outer_size_x - (self.padding.left + self.padding.right), - outer_size_y - (self.padding.top + self.padding.bottom), - ) - } -} - -impl UiElement for Container { - fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response { - let mut size = Vec2::ZERO; - //if matches!(self.size.0, UiSize::Auto) || matches!(self.size.1, UiSize::Auto) { - let mut leftover_gap = Vec2::ZERO; - for element in &self.elements { - let measure = element.measure(state, &LayoutInfo { - position: layout.position + size, - max_size: self.measure_max_inner_size(layout), // - size TODO - direction: self.direction, - }); - match self.direction { - UiDirection::Horizontal => { - size.x += measure.size.x + self.gap; - size.y = size.y.max(measure.size.y); - leftover_gap.x = self.gap; - }, - UiDirection::Vertical => { - size.x = size.x.max(measure.size.x); - size.y += measure.size.y + self.gap; - leftover_gap.y = self.gap; - } - } - } - size -= leftover_gap; - - let inner_content_size = Some(size); - - size += vec2( - self.padding.left + self.padding.right, - self.padding.top + self.padding.bottom, - ); - - match self.size.0 { - UiSize::Auto => (), - UiSize::Percentage(percentage) => size.x = layout.max_size.x * percentage, - UiSize::Pixels(pixels) => size.x = pixels, - } - match self.size.1 { - UiSize::Auto => (), - UiSize::Percentage(percentage) => size.y = layout.max_size.y * percentage, - UiSize::Pixels(pixels) => size.y = pixels, - } - - Response { - size, - hints: Hints { - inner_content_size, - ..Default::default() - }, - user_data: None - } - } - - fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) { - let mut position = layout.position; - - //background - if let Some(color) = self.background { - draw.add(UiDrawCommand::Rectangle { - position, - size: measure.size, - color - }); - } - - //padding - position += vec2(self.padding.left, self.padding.top); - - //alignment - match (self.align.0, self.direction) { - (Alignment::Begin, _) => (), - (Alignment::Center, UiDirection::Horizontal) => { - position.x += (measure.size.x - measure.hints.inner_content_size.unwrap().x) / 2.; - }, - (Alignment::Center, UiDirection::Vertical) => { - position.y += (measure.size.y - measure.hints.inner_content_size.unwrap().y) / 2.; - }, - (Alignment::End, UiDirection::Horizontal) => { - position.x += measure.size.x - measure.hints.inner_content_size.unwrap().x - self.padding.right - self.padding.left; - }, - (Alignment::End, UiDirection::Vertical) => { - position.y += measure.size.y - measure.hints.inner_content_size.unwrap().y - self.padding.bottom - self.padding.top; - } - } - - for element in &self.elements { - //(passing max size from layout rather than actual bounds for the sake of consistency with measure() above) - - let mut el_layout = LayoutInfo { - position, - max_size: self.measure_max_inner_size(layout), - direction: self.direction, - }; - - //measure - let el_measure = element.measure(state, &el_layout); - - //align (on sec. axis) - match (self.align.1, self.direction) { - (Alignment::Begin, _) => (), - (Alignment::Center, UiDirection::Horizontal) => { - el_layout.position.y += (measure.size.y - self.padding.bottom - self.padding.top - el_measure.size.y) / 2.; - }, - (Alignment::Center, UiDirection::Vertical) => { - el_layout.position.x += (measure.size.x - self.padding.left - self.padding.right - el_measure.size.x) / 2.; - }, - (Alignment::End, UiDirection::Horizontal) => { - el_layout.position.y += measure.size.y - el_measure.size.y - self.padding.bottom; - }, - (Alignment::End, UiDirection::Vertical) => { - el_layout.position.x += measure.size.x - el_measure.size.x - self.padding.right; - } - } - - //process - element.process(&el_measure, state, &el_layout, draw); - - //layout - match self.direction { - UiDirection::Horizontal => { - position.x += el_measure.size.x + self.gap; - }, - UiDirection::Vertical => { - position.y += el_measure.size.y + self.gap; - } - } - } - } -} diff --git a/kubi-ui/src/element/builtin/progress_bar.rs b/kubi-ui/src/element/builtin/progress_bar.rs deleted file mode 100644 index 35283c1..0000000 --- a/kubi-ui/src/element/builtin/progress_bar.rs +++ /dev/null @@ -1,70 +0,0 @@ -use glam::{vec2, Vec4, vec4}; -use crate::{ - UiSize, LayoutInfo, - draw::{UiDrawCommand, UiDrawCommands}, - measure::Response, - state::StateRepo, - element::UiElement -}; - -#[derive(Debug, Clone, Copy)] -pub struct ProgressBar { - pub size: (UiSize, UiSize), - pub value: f32, - pub color_foreground: Vec4, - pub color_background: Vec4, -} - -impl Default for ProgressBar { - fn default() -> Self { - Self { - size: (UiSize::Auto, UiSize::Auto), - value: 0., - color_foreground: vec4(0.0, 0.0, 1.0, 1.0), - color_background: vec4(0.0, 0.0, 0.0, 1.0), - } - } -} - -const BAR_HEIGHT: f32 = 20.0; - -impl UiElement for ProgressBar { - fn name(&self) -> &'static str { "Progress bar" } - - fn measure(&self, _: &StateRepo, layout: &LayoutInfo) -> Response { - Response { - size: vec2( - match self.size.0 { - UiSize::Auto => layout.max_size.x.max(300.), - UiSize::Percentage(p) => layout.max_size.x * p, - UiSize::Pixels(p) => p, - }, - match self.size.1 { - UiSize::Auto => BAR_HEIGHT, - UiSize::Percentage(p) => layout.max_size.y * p, - UiSize::Pixels(p) => p, - } - ), - hints: Default::default(), - user_data: None, - } - } - - fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) { - let value = self.value.clamp(0., 1.); - if value < 1. { - draw.add(UiDrawCommand::Rectangle { - position: layout.position, - size: measure.size, - color: self.color_background - }); - } - if value > 0. { - draw.add(UiDrawCommand::Rectangle { - position: layout.position, - size: measure.size * vec2(value, 1.0), - color: self.color_foreground - }); - } - } -} diff --git a/kubi-ui/src/element/builtin/rect.rs b/kubi-ui/src/element/builtin/rect.rs deleted file mode 100644 index de082f8..0000000 --- a/kubi-ui/src/element/builtin/rect.rs +++ /dev/null @@ -1,54 +0,0 @@ -use glam::{vec2, Vec4}; -use crate::{ - LayoutInfo, - UiSize, - element::UiElement, - state::StateRepo, - measure::Response, - draw::{UiDrawCommand, UiDrawCommands} -}; - -pub struct Rect { - pub size: (UiSize, UiSize), - pub color: Option, -} - -impl Default for Rect { - fn default() -> Self { - Self { - size: (UiSize::Pixels(10.), UiSize::Pixels(10.)), - color: Some(Vec4::new(0., 0., 0., 0.5)), - } - } -} - -impl UiElement for Rect { - fn measure(&self, _state: &StateRepo, layout: &LayoutInfo) -> Response { - Response { - size: vec2( - match self.size.0 { - UiSize::Auto => layout.max_size.x, - UiSize::Percentage(percentage) => layout.max_size.x * percentage, - UiSize::Pixels(pixels) => pixels, - }, - match self.size.1 { - UiSize::Auto => layout.max_size.y, - UiSize::Percentage(percentage) => layout.max_size.y * percentage, - UiSize::Pixels(pixels) => pixels, - }, - ), - hints: Default::default(), - user_data: None - } - } - - fn process(&self, measure: &Response, _state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) { - if let Some(color) = self.color { - draw.add(UiDrawCommand::Rectangle { - position: layout.position, - size: measure.size, - color, - }); - } - } -} diff --git a/kubi-ui/src/element/builtin/spacer.rs b/kubi-ui/src/element/builtin/spacer.rs deleted file mode 100644 index eeddcd6..0000000 --- a/kubi-ui/src/element/builtin/spacer.rs +++ /dev/null @@ -1,32 +0,0 @@ -use glam::vec2; -use crate::{ - LayoutInfo, - UiDirection, - element::UiElement, - state::StateRepo, - measure::Response, - draw::{UiDrawCommand, UiDrawCommands} -}; - -pub struct Spacer(pub f32); - -impl Default for Spacer { - fn default() -> Self { - Self(5.) - } -} - -impl UiElement for Spacer { - fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response { - Response { - size: match layout.direction { - UiDirection::Horizontal => vec2(self.0, 0.), - UiDirection::Vertical => vec2(0., self.0), - }, - hints: Default::default(), - user_data: None - } - } - - fn process(&self, _measure: &Response, _state: &mut StateRepo, _layout: &LayoutInfo, _draw: &mut UiDrawCommands) {} -} diff --git a/kubi-ui/src/element/builtin/text.rs b/kubi-ui/src/element/builtin/text.rs deleted file mode 100644 index b8fdbb5..0000000 --- a/kubi-ui/src/element/builtin/text.rs +++ /dev/null @@ -1,61 +0,0 @@ -use std::borrow::Cow; -use glam::{vec2, Vec4}; -use crate::{ - LayoutInfo, - UiSize, - element::UiElement, - state::StateRepo, - measure::Response, - draw::{UiDrawCommand, UiDrawCommands}, text::FontHandle -}; - -pub struct Text { - pub text: Cow<'static, str>, - pub size: (UiSize, UiSize), - pub color: Vec4, - pub font: FontHandle, - pub text_size: u8, -} - -impl Default for Text { - fn default() -> Self { - Self { - text: "".into(), - size: (UiSize::Auto, UiSize::Auto), - color: Vec4::new(1., 1., 1., 1.), - font: FontHandle(0), - text_size: 16, - } - } -} - -impl UiElement for Text { - fn measure(&self, _state: &StateRepo, layout: &LayoutInfo) -> Response { - Response { - size: vec2( - match self.size.0 { - UiSize::Auto => layout.max_size.x, - UiSize::Percentage(percentage) => layout.max_size.x * percentage, - UiSize::Pixels(pixels) => pixels, - }, - match self.size.1 { - UiSize::Auto => self.text_size as f32, - UiSize::Percentage(percentage) => layout.max_size.y * percentage, - UiSize::Pixels(pixels) => pixels, - }, - ), - hints: Default::default(), - user_data: None - } - } - - fn process(&self, _measure: &Response, _state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) { - draw.add(UiDrawCommand::Text { - text: self.text.clone(), - position: layout.position, - size: self.text_size, - color: self.color, - font: self.font - }); - } -} diff --git a/kubi-ui/src/event.rs b/kubi-ui/src/event.rs deleted file mode 100644 index c488363..0000000 --- a/kubi-ui/src/event.rs +++ /dev/null @@ -1,10 +0,0 @@ -use glam::Vec2; - -pub enum UiEvent { - MouseMove(Vec2), - MouseDown(Vec2), - MouseUp(Vec2), - KeyDown(u32), - KeyUp(u32), - TextInput(char), -} diff --git a/kubi-ui/src/interaction.rs b/kubi-ui/src/interaction.rs deleted file mode 100644 index f172ade..0000000 --- a/kubi-ui/src/interaction.rs +++ /dev/null @@ -1,51 +0,0 @@ -use crate::{element::UiElement, draw::UiDrawCommands}; - -pub struct Interactable { - pub element: T, - pub hovered: Option>, - pub clicked: Option>, -} - -impl Interactable { - pub fn new(element: T) -> Self { - Self { - element, - hovered: None, - clicked: None, - } - } - - pub fn on_click(self, clicked: impl FnOnce() + 'static) -> Self { - Self { - clicked: Some(Box::new(clicked)), - ..self - } - } - - pub fn on_hover(self, clicked: impl FnOnce() + 'static) -> Self { - Self { - clicked: Some(Box::new(clicked)), - ..self - } - } -} - -impl UiElement for Interactable { - fn measure(&self, state: &crate::state::StateRepo, layout: &crate::LayoutInfo) -> crate::measure::Response { - self.element.measure(state, layout) - } - - fn process(&self, measure: &crate::measure::Response, state: &mut crate::state::StateRepo, layout: &crate::LayoutInfo, draw: &mut UiDrawCommands) { - self.element.process(measure, state, layout, draw) - } -} - -pub trait IntoInteractable: UiElement { - fn into_interactable(self) -> Interactable; -} - -impl IntoInteractable for T { - fn into_interactable(self) -> Interactable { - Interactable::new(self) - } -} diff --git a/kubi-ui/src/lib.rs b/kubi-ui/src/lib.rs deleted file mode 100644 index a2b4aac..0000000 --- a/kubi-ui/src/lib.rs +++ /dev/null @@ -1,129 +0,0 @@ -use glam::Vec2; - -pub mod element; -pub mod event; -pub mod draw; -pub mod measure; -pub mod state; -pub mod text; -pub mod interaction; - -use element::UiElement; -use state::StateRepo; -use draw::{UiDrawCommands, UiDrawPlan}; -use text::{TextRenderer, FontTextureInfo, FontHandle}; - -// pub struct ElementContext<'a> { -// pub state: &'a mut StateRepo, -// pub draw: &'a mut UiDrawCommands, -// pub text: &'a mut TextRenderer, -// } -pub trait IfModified { - fn if_modified(&self) -> Option<&T>; -} - -pub struct KubiUi { - //mouse_position: Vec2, - stateful_state: StateRepo, - //event_queue: VecDeque, - prev_draw_commands: UiDrawCommands, - draw_commands: UiDrawCommands, - draw_plan: UiDrawPlan, - draw_plan_modified: bool, - text_renderer: TextRenderer, -} - -impl KubiUi { - pub fn new() -> Self { - KubiUi { - //mouse_position: Vec2::ZERO, - stateful_state: StateRepo::default(), - //event_queue: VecDeque::new(), - // root_elements: Vec::new(), - prev_draw_commands: UiDrawCommands::default(), - draw_commands: UiDrawCommands::default(), - draw_plan: UiDrawPlan::default(), - draw_plan_modified: false, - // ftm: FontTextureManager::default(), - text_renderer: TextRenderer::new(), - } - } - - pub fn add_font_from_bytes(&mut self, font: &[u8]) -> FontHandle { - self.text_renderer.add_font_from_bytes(font) - } - - pub fn add(&mut self, element: T, max_size: Vec2) { - let layout = LayoutInfo { - position: Vec2::ZERO, - max_size, - direction: UiDirection::Vertical, - }; - let measure = element.measure(&self.stateful_state, &layout); - element.process(&measure, &mut self.stateful_state, &layout, &mut self.draw_commands); - } - - pub fn begin(&mut self) { - std::mem::swap(&mut self.prev_draw_commands, &mut self.draw_commands); - self.draw_plan_modified = false; - self.draw_commands.commands.clear(); - self.text_renderer.reset_frame(); - } - - pub fn end(&mut self) { - if self.draw_commands.commands == self.prev_draw_commands.commands { - return - } - self.draw_plan = UiDrawPlan::build(&self.draw_commands, &mut self.text_renderer); - self.draw_plan_modified = true; - } - - pub fn draw_plan(&self) -> (bool, &UiDrawPlan) { - (self.draw_plan_modified, &self.draw_plan) - } - - pub fn font_texture(&self) -> FontTextureInfo { - self.text_renderer.font_texture() - } -} - -impl Default for KubiUi { - fn default() -> Self { - Self::new() - } -} - -#[derive(Default, Debug, Clone, Copy)] -pub enum UiSize { - #[default] - Auto, - Percentage(f32), - Pixels(f32), -} - -#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum UiDirection { - #[default] - Vertical, - Horizontal, -} - -pub struct LayoutInfo { - ///Not availabe during measuring step - pub position: Vec2, - pub max_size: Vec2, - pub direction: UiDirection, -} - -pub struct ElementList(Vec>); - -impl ElementList { - pub fn add(&mut self, element: impl UiElement + 'static) { - self.0.push(Box::new(element)); - } -} -pub fn elements(f: impl FnOnce(&mut ElementList)) -> Vec> { - let mut elements = ElementList(Vec::new()); - f(&mut elements); - elements.0 -} diff --git a/kubi-ui/src/measure.rs b/kubi-ui/src/measure.rs deleted file mode 100644 index 9a83832..0000000 --- a/kubi-ui/src/measure.rs +++ /dev/null @@ -1,15 +0,0 @@ -use glam::Vec2; - -#[derive(Default)] -#[non_exhaustive] -pub struct Hints { - pub inner_content_size: Option, - pub inner_content_size_cache: Option>, -} - -#[derive(Default)] -pub struct Response { - pub size: Vec2, - pub hints: Hints, - pub user_data: Option>, -} diff --git a/kubi-ui/src/state.rs b/kubi-ui/src/state.rs deleted file mode 100644 index a24d671..0000000 --- a/kubi-ui/src/state.rs +++ /dev/null @@ -1,9 +0,0 @@ -use hashbrown::{HashMap, HashSet}; -use nohash_hasher::BuildNoHashHasher; -use std::any::Any; - -#[derive(Default)] -pub struct StateRepo { - state: HashMap, BuildNoHashHasher>, - active_ids: HashSet> -} diff --git a/kubi-ui/src/text.rs b/kubi-ui/src/text.rs deleted file mode 100644 index 5e99e08..0000000 --- a/kubi-ui/src/text.rs +++ /dev/null @@ -1,50 +0,0 @@ -use std::sync::Arc; - -mod font; -mod ftm; - -use font::FontManager; -pub use font::FontHandle; -use fontdue::{Font, FontSettings}; -use ftm::FontTextureManager; -pub use ftm::{FontTextureInfo, GlyphCacheEntry}; - -pub struct TextRenderer { - fm: FontManager, - ftm: FontTextureManager, -} - -impl TextRenderer { - pub fn new() -> Self { - Self { - fm: FontManager::new(), - ftm: FontTextureManager::default(), - } - } - - pub fn add_font_from_bytes(&mut self, font: &[u8]) -> FontHandle { - self.fm.add_font(Font::from_bytes(font, FontSettings::default()).unwrap()) - } - - pub fn reset_frame(&mut self) { - self.ftm.reset_modified(); - } - - pub fn font_texture(&self) -> FontTextureInfo { - self.ftm.info() - } - - pub fn glyph(&mut self, font_handle: FontHandle, character: char, size: u8) -> Arc { - self.ftm.glyph(&self.fm, font_handle, character, size) - } - - pub(crate) fn internal_font(&self, handle: FontHandle) -> &Font { - self.fm.get(handle).unwrap() - } -} - -impl Default for TextRenderer { - fn default() -> Self { - Self::new() - } -} diff --git a/kubi-ui/src/text/font.rs b/kubi-ui/src/text/font.rs deleted file mode 100644 index ca381aa..0000000 --- a/kubi-ui/src/text/font.rs +++ /dev/null @@ -1,44 +0,0 @@ -use fontdue::Font; - -#[cfg(feature = "builtin_font")] -const BIN_FONT: &[u8] = include_bytes!("../../assets/font/ProggyTiny.ttf"); - -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] -pub struct FontHandle(pub(crate) usize); - -#[cfg(feature = "builtin_font")] -pub const BUILTIN_FONT: FontHandle = FontHandle(0); - -pub struct FontManager { - fonts: Vec, -} - -impl FontManager { - pub fn new() -> Self { - let mut this = Self { - fonts: Vec::new(), - }; - #[cfg(feature = "builtin_font")] - { - let font = Font::from_bytes(BIN_FONT, fontdue::FontSettings::default()).unwrap(); - this.add_font(font); - }; - this - } - - /// Add a (fontdue) font to the renderer. - pub fn add_font(&mut self, font: Font) -> FontHandle { - self.fonts.push(font); - FontHandle(self.fonts.len() - 1) - } - - pub fn get(&self, handle: FontHandle) -> Option<&Font> { - self.fonts.get(handle.0) - } -} - -impl Default for FontManager { - fn default() -> Self { - Self::new() - } -} diff --git a/kubi-ui/src/text/ftm.rs b/kubi-ui/src/text/ftm.rs deleted file mode 100644 index 36c28c2..0000000 --- a/kubi-ui/src/text/ftm.rs +++ /dev/null @@ -1,139 +0,0 @@ -use std::sync::Arc; -use fontdue::Metrics; -use glam::{IVec2, UVec2, uvec2, ivec2}; -use hashbrown::HashMap; -use rect_packer::DensePacker; - -use crate::IfModified; - -use super::font::{FontHandle, FontManager}; - -#[derive(PartialEq, Eq, Hash)] -struct GlyphCacheKey { - font_index: usize, - character: char, - size: u8, -} - -pub struct GlyphCacheEntry { - pub data: Vec, - pub metrics: Metrics, - pub position: IVec2, - pub size: UVec2, -} - -#[derive(Clone, Copy, Debug)] -pub struct FontTextureInfo<'a> { - pub modified: bool, - pub data: &'a [u8], - pub size: UVec2, -} - -impl<'a> IfModified> for FontTextureInfo<'a> { - fn if_modified(&self) -> Option<&Self> { - match self.modified { - true => Some(self), - false => None, - } - } -} - -// impl<'a> FontTextureInfo<'a> { -// fn if_modified(&self) -> Option { -// match self.modified { -// true => Some(*self), -// false => None, -// } -// } -// } - -pub struct FontTextureManager { - glyph_cache: HashMap>, - packer: DensePacker, - font_texture: Vec, - font_texture_size: UVec2, - modified: bool, -} - -impl FontTextureManager { - pub fn new(size: UVec2) -> Self { - FontTextureManager { - glyph_cache: HashMap::new(), - packer: DensePacker::new(size.x as i32, size.y as i32), - font_texture: vec![0; (size.x * size.y * 4) as usize], - font_texture_size: size, - modified: false, - } - } - - pub fn reset_modified(&mut self) { - self.modified = false; - } - - pub fn info(&self) -> FontTextureInfo { - FontTextureInfo { - modified: self.modified, - data: &self.font_texture, - size: self.font_texture_size, - } - } - - /// Either looks up the glyph in the cache or renders it and adds it to the cache. - pub fn glyph(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> Arc { - let key = GlyphCacheKey { - font_index: font_handle.0, - character, - size, - }; - if let Some(entry) = self.glyph_cache.get(&key) { - return Arc::clone(entry); - } - let font = font_manager.get(font_handle).unwrap(); - let (metrics, bitmap) = font.rasterize(character, size as f32); - log::debug!("rasterized glyph: {}, {:?}, {:?}", character, metrics, bitmap); - let texture_position = self.packer.pack(metrics.width as i32, metrics.height as i32, false).unwrap(); - let texture_size = uvec2(metrics.width as u32, metrics.height as u32); - let entry = Arc::new(GlyphCacheEntry { - data: bitmap, - metrics, - position: ivec2(texture_position.x, texture_position.y), - size: texture_size, - }); - self.glyph_cache.insert_unique_unchecked(key, Arc::clone(&entry)); - self.glyph_place(&entry); - self.modified = true; - entry - } - - /// Place glyph onto the font texture. - fn glyph_place(&mut self, entry: &GlyphCacheEntry) { - let tex_size = self.font_texture_size; - let GlyphCacheEntry { size, position, data, .. } = entry; - //println!("{size:?} {position:?}"); - for y in 0..size.y { - for x in 0..size.x { - let src = (size.x * y + x) as usize; - let dst = (tex_size.x * (y + position.y as u32) + (x + position.x as u32)) as usize * 4; - self.font_texture[dst..=(dst + 3)].copy_from_slice(&[255, 255, 255, data[src]]); - //print!("{} ", if data[src] > 0 {'#'} else {'.'}); - //print!("{src} {dst} / "); - } - //println!(); - } - } - - // pub fn glyph(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> Arc { - // let (is_new, glyph) = self.glyph_allocate(font_manager, font_handle, character, size); - // if is_new { - // self.glyph_place(&glyph); - // self.modified = true; - // } - // glyph - // } -} - -impl Default for FontTextureManager { - fn default() -> Self { - Self::new(uvec2(1024, 1024)) - } -} diff --git a/kubi/Cargo.toml b/kubi/Cargo.toml index 7eed1f8..1b7aec2 100644 --- a/kubi/Cargo.toml +++ b/kubi/Cargo.toml @@ -11,8 +11,8 @@ crate-type = ["lib", "cdylib"] [dependencies] kubi-shared = { path = "../kubi-shared" } kubi-logging = { path = "../kubi-logging" } -kubi-ui = { path = "../kubi-ui" } -kubi-ui-glium = { path = "../kubi-ui-glium" } +hui = { version = "^0.0", git = "https://github.com/griffi-gh/hui", rev = "1e1dccde0c" } +hui-glium = { version = "^0.0", git = "https://github.com/griffi-gh/hui", rev = "1e1dccde0c" } log = "0.4" glium = { git = "https://github.com/glium/glium", rev = "a352c667" } glutin = "0.31" diff --git a/kubi/src/kubi_ui_integration.rs b/kubi/src/hui_integration.rs similarity index 77% rename from kubi/src/kubi_ui_integration.rs rename to kubi/src/hui_integration.rs index 040abed..46a085f 100644 --- a/kubi/src/kubi_ui_integration.rs +++ b/kubi/src/hui_integration.rs @@ -1,43 +1,43 @@ -use kubi_ui::KubiUi; -use kubi_ui_glium::GliumUiRenderer; -use shipyard::{AllStoragesView, Unique, UniqueView, NonSendSync, UniqueViewMut}; -use crate::rendering::{Renderer, RenderTarget, WindowSize}; - -#[derive(Unique)] -pub struct UiState { - pub kui: KubiUi, - pub renderer: GliumUiRenderer, -} - -pub fn kubi_ui_init( - storages: AllStoragesView -) { - let renderer = storages.borrow::>>().unwrap(); - storages.add_unique_non_send_sync(UiState { - kui: KubiUi::new(), - renderer: GliumUiRenderer::new(&renderer.display) - }); -} - -pub fn kubi_ui_begin( - mut ui: NonSendSync> -) { - ui.kui.begin(); -} - -pub fn kubi_ui_end( - mut ui: NonSendSync> -) { - let ui: &mut UiState = &mut ui; - let UiState { kui, renderer } = ui; - kui.end(); - renderer.update(kui); -} - -pub fn kubi_ui_draw( - ui: NonSendSync>, - mut target: NonSendSync>, - size: UniqueView -) { - ui.renderer.draw(&mut target.0, size.0.as_vec2()); -} +use hui::UiInstance; +use hui_glium::GliumUiRenderer; +use shipyard::{AllStoragesView, Unique, UniqueView, NonSendSync, UniqueViewMut}; +use crate::rendering::{Renderer, RenderTarget, WindowSize}; + +#[derive(Unique)] +pub struct UiState { + pub hui: UiInstance, + pub renderer: GliumUiRenderer, +} + +pub fn kubi_ui_init( + storages: AllStoragesView +) { + let renderer = storages.borrow::>>().unwrap(); + storages.add_unique_non_send_sync(UiState { + hui: UiInstance::new(), + renderer: GliumUiRenderer::new(&renderer.display) + }); +} + +pub fn kubi_ui_begin( + mut ui: NonSendSync> +) { + ui.hui.begin(); +} + +pub fn kubi_ui_end( + mut ui: NonSendSync> +) { + let ui: &mut UiState = &mut ui; + let UiState { hui, renderer } = ui; + hui.end(); + renderer.update(hui); +} + +pub fn kubi_ui_draw( + ui: NonSendSync>, + mut target: NonSendSync>, + size: UniqueView +) { + ui.renderer.draw(&mut target.0, size.0.as_vec2()); +} diff --git a/kubi/src/lib.rs b/kubi/src/lib.rs index 9fc7b42..a8422bb 100644 --- a/kubi/src/lib.rs +++ b/kubi/src/lib.rs @@ -29,7 +29,7 @@ pub(crate) mod delta_time; pub(crate) mod cursor_lock; pub(crate) mod control_flow; pub(crate) mod state; -pub(crate) mod kubi_ui_integration; +pub(crate) mod hui_integration; pub(crate) mod networking; pub(crate) mod init; pub(crate) mod color; @@ -77,7 +77,7 @@ use control_flow::{exit_on_esc, insert_control_flow_unique, RequestExit}; use state::{is_ingame, is_ingame_or_loading, is_loading, init_state, update_state, is_connecting}; use networking::{update_networking, update_networking_late, is_multiplayer, disconnect_on_exit, is_singleplayer}; use init::initialize_from_args; -use kubi_ui_integration::{kubi_ui_init, kubi_ui_begin, kubi_ui_end, kubi_ui_draw}; +use hui_integration::{kubi_ui_init, kubi_ui_begin, kubi_ui_end, kubi_ui_draw}; use loading_screen::update_loading_screen; use connecting_screen::switch_to_loading_if_connected; use fixed_timestamp::init_fixed_timestamp_storage; diff --git a/kubi/src/loading_screen.rs b/kubi/src/loading_screen.rs index 6e84fd3..eeba2d9 100644 --- a/kubi/src/loading_screen.rs +++ b/kubi/src/loading_screen.rs @@ -1,60 +1,60 @@ -use kubi_ui::element::progress_bar::ProgressBar; -use shipyard::{UniqueView, UniqueViewMut, Workload, NonSendSync, IntoWorkload}; -use winit::keyboard::KeyCode; -use crate::{ - world::ChunkStorage, - state::{GameState, NextState}, - rendering::WindowSize, - input::RawKbmInputState, - kubi_ui_integration::UiState, -}; - -fn render_progressbar( - mut ui: NonSendSync>, - world: UniqueView, - size: UniqueView -) { - let value = { - let loaded = world.chunks.iter().fold(0, |acc, (&_, chunk)| { - acc + chunk.desired_state.matches_current(chunk.current_state) as usize - }); - let total = world.chunks.len(); - loaded as f32 / total as f32 - }; - ui.kui.add( - ProgressBar { value, ..Default::default() }, - size.0.as_vec2() - ); -} - -fn switch_to_ingame_if_loaded( - world: UniqueView, - mut state: UniqueViewMut -) { - if world.chunks.is_empty() { - return - } - if world.chunks.iter().all(|(_, chunk)| { - chunk.desired_state.matches_current(chunk.current_state) - }) { - log::info!("Finished loading chunks"); - state.0 = Some(GameState::InGame); - } -} - -fn override_loading( - kbm_state: UniqueView, - mut state: UniqueViewMut -) { - if kbm_state.keyboard_state.contains(KeyCode::KeyF as u32) { - state.0 = Some(GameState::InGame); - } -} - -pub fn update_loading_screen() -> Workload { - ( - render_progressbar, - override_loading, - switch_to_ingame_if_loaded, - ).into_sequential_workload() -} +use hui::element::progress_bar::ProgressBar; +use shipyard::{UniqueView, UniqueViewMut, Workload, NonSendSync, IntoWorkload}; +use winit::keyboard::KeyCode; +use crate::{ + world::ChunkStorage, + state::{GameState, NextState}, + rendering::WindowSize, + input::RawKbmInputState, + hui_integration::UiState, +}; + +fn render_progressbar( + mut ui: NonSendSync>, + world: UniqueView, + size: UniqueView +) { + let value = { + let loaded = world.chunks.iter().fold(0, |acc, (&_, chunk)| { + acc + chunk.desired_state.matches_current(chunk.current_state) as usize + }); + let total = world.chunks.len(); + loaded as f32 / total as f32 + }; + ui.hui.add( + ProgressBar { value, ..Default::default() }, + size.0.as_vec2() + ); +} + +fn switch_to_ingame_if_loaded( + world: UniqueView, + mut state: UniqueViewMut +) { + if world.chunks.is_empty() { + return + } + if world.chunks.iter().all(|(_, chunk)| { + chunk.desired_state.matches_current(chunk.current_state) + }) { + log::info!("Finished loading chunks"); + state.0 = Some(GameState::InGame); + } +} + +fn override_loading( + kbm_state: UniqueView, + mut state: UniqueViewMut +) { + if kbm_state.keyboard_state.contains(KeyCode::KeyF as u32) { + state.0 = Some(GameState::InGame); + } +} + +pub fn update_loading_screen() -> Workload { + ( + render_progressbar, + override_loading, + switch_to_ingame_if_loaded, + ).into_sequential_workload() +}