mirror of
https://github.com/griffi-gh/kubi.git
synced 2024-11-22 06:48:43 -06:00
Compare commits
8 commits
0f93d0ca71
...
6b33e9cdc9
Author | SHA1 | Date | |
---|---|---|---|
griffi-gh | 6b33e9cdc9 | ||
griffi-gh | f19031662f | ||
griffi-gh | 491bb435cc | ||
griffi-gh | eaf4d98d65 | ||
griffi-gh | e1b41bbc79 | ||
griffi-gh | 5823f05943 | ||
griffi-gh | dea9b7c584 | ||
griffi-gh | 207f29e0ee |
30
Cargo.lock
generated
30
Cargo.lock
generated
|
@ -350,9 +350,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.3"
|
||||
version = "0.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146"
|
||||
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
|
||||
dependencies = [
|
||||
"core-foundation-sys",
|
||||
"libc",
|
||||
|
@ -360,9 +360,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.4"
|
||||
version = "0.8.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
|
||||
checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
|
||||
|
||||
[[package]]
|
||||
name = "core-graphics"
|
||||
|
@ -379,9 +379,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "core-graphics-types"
|
||||
version = "0.1.2"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2bb142d41022986c1d8ff29103a1411c8a3dfad3552f87a4f8dc50d61d4f4e33"
|
||||
checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"
|
||||
dependencies = [
|
||||
"bitflags 1.3.2",
|
||||
"core-foundation",
|
||||
|
@ -1124,9 +1124,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.11"
|
||||
version = "0.4.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "969488b55f8ac402214f3f5fd243ebb7206cf82de60d3172994707a4bcc2b829"
|
||||
checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
|
@ -1659,15 +1659,15 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.25"
|
||||
version = "0.38.26"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc99bc2d4f1fed22595588a013687477aedf3cdcfb26558c559edb67b4d9b22e"
|
||||
checksum = "9470c4bf8246c8daf25f9598dca807fb6510347b1e1cfa55749113850c79d88a"
|
||||
dependencies = [
|
||||
"bitflags 2.4.1",
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.48.0",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
@ -2672,18 +2672,18 @@ checksum = "0fcb9cbac069e033553e8bb871be2fbdffcab578eb25bd0f7c508cedc6dcd75a"
|
|||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.7.26"
|
||||
version = "0.7.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e97e415490559a91254a2979b4829267a57d2fcd741a98eee8b722fb57289aa0"
|
||||
checksum = "7d6f15f7ade05d2a4935e34a457b936c23dc70a05cc1d97133dc99e7a3fe0f0e"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.7.26"
|
||||
version = "0.7.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd7e48ccf166952882ca8bd778a43502c64f33bf94c12ebe2a7f08e5a0f6689f"
|
||||
checksum = "dbbad221e3f78500350ecbd7dfa4e63ef945c05f4c61cb7f4d3f84cd0bba649b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
|
202
assets/fonts/roboto/LICENSE.txt
Normal file
202
assets/fonts/roboto/LICENSE.txt
Normal file
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
BIN
assets/fonts/roboto/Roboto-Regular.ttf
Normal file
BIN
assets/fonts/roboto/Roboto-Regular.ttf
Normal file
Binary file not shown.
72
kubi-ui-examples/examples/text.rs
Normal file
72
kubi-ui-examples/examples/text.rs
Normal file
|
@ -0,0 +1,72 @@
|
|||
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, text::Text
|
||||
},
|
||||
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 font_handle = kui.add_font_from_bytes(include_bytes!("../../assets/fonts/roboto/Roboto-Regular.ttf"));
|
||||
|
||||
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 {
|
||||
gap: 5.,
|
||||
padding: Sides::all(5.),
|
||||
align: (Alignment::Begin, Alignment::Begin),
|
||||
size: (UiSize::Percentage(1.), UiSize::Percentage(1.)),
|
||||
elements: vec![
|
||||
Box::new(Text {
|
||||
text: "Hello_world".into(),
|
||||
font: font_handle,
|
||||
..Default::default()
|
||||
}),
|
||||
],
|
||||
..Default::default()
|
||||
}, resolution);
|
||||
|
||||
kui.end();
|
||||
|
||||
backend.update(&kui);
|
||||
backend.draw(&mut frame, resolution);
|
||||
|
||||
frame.finish().unwrap();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
|
@ -1,11 +1,21 @@
|
|||
#version 300 es
|
||||
|
||||
precision highp float;
|
||||
precision highp sampler2D;
|
||||
|
||||
out vec4 out_color;
|
||||
in vec4 vtx_color;
|
||||
in vec2 vtx_uv;
|
||||
uniform bool use_tex;
|
||||
uniform sampler2D tex;
|
||||
|
||||
void main() {
|
||||
if (vtx_color.w <= 0.) discard;
|
||||
out_color = vtx_color;
|
||||
//if (vtx_color.w <= 0.) discard;
|
||||
vec4 tex_color;
|
||||
if (use_tex) {
|
||||
tex_color = texture(tex, vtx_uv);
|
||||
} else {
|
||||
tex_color = vec4(1.);
|
||||
}
|
||||
out_color = tex_color * vtx_color;
|
||||
}
|
||||
|
|
|
@ -3,12 +3,15 @@
|
|||
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.);
|
||||
}
|
||||
|
|
|
@ -1,14 +1,17 @@
|
|||
use std::rc::Rc;
|
||||
use glam::Vec2;
|
||||
use glium::{
|
||||
Surface, DrawParameters, Blend,
|
||||
Program, VertexBuffer, IndexBuffer,
|
||||
backend::Facade,
|
||||
backend::{Facade, Context},
|
||||
texture::{SrgbTexture2d, RawImage2d},
|
||||
index::PrimitiveType,
|
||||
implement_vertex, uniform, texture::{SrgbTexture2d, RawImage2d},
|
||||
implement_vertex,
|
||||
uniform, uniforms::DynamicUniforms,
|
||||
};
|
||||
use kubi_ui::{
|
||||
KubiUi,
|
||||
draw::{UiDrawPlan, UiVertex},
|
||||
draw::{UiDrawPlan, UiVertex, BindTexture},
|
||||
text::FontTextureInfo, IfModified,
|
||||
};
|
||||
|
||||
|
@ -36,10 +39,10 @@ impl From<UiVertex> for Vertex {
|
|||
implement_vertex!(Vertex, position, color, uv);
|
||||
|
||||
struct BufferPair {
|
||||
vertex_buffer: glium::VertexBuffer<Vertex>,
|
||||
index_buffer: glium::IndexBuffer<u32>,
|
||||
vertex_count: usize,
|
||||
index_count: usize,
|
||||
pub vertex_buffer: glium::VertexBuffer<Vertex>,
|
||||
pub index_buffer: glium::IndexBuffer<u32>,
|
||||
pub vertex_count: usize,
|
||||
pub index_count: usize,
|
||||
}
|
||||
|
||||
impl BufferPair {
|
||||
|
@ -102,65 +105,121 @@ impl BufferPair {
|
|||
}
|
||||
}
|
||||
|
||||
pub struct GliumUiRenderer {
|
||||
program: glium::Program,
|
||||
struct GlDrawCall {
|
||||
active: bool,
|
||||
buffer: BufferPair,
|
||||
bind_texture: Option<Rc<SrgbTexture2d>>,
|
||||
}
|
||||
|
||||
pub struct GliumUiRenderer {
|
||||
context: Rc<Context>,
|
||||
program: glium::Program,
|
||||
font_texture: Option<Rc<SrgbTexture2d>>,
|
||||
plan: Vec<GlDrawCall>,
|
||||
}
|
||||
|
||||
impl GliumUiRenderer {
|
||||
pub fn new<F: Facade>(facade: &F) -> Self {
|
||||
log::info!("init glium backend for ui");
|
||||
log::debug!("init program");
|
||||
let program = Program::from_source(facade, VERTEX_SHADER, FRAGMENT_SHADER, None).unwrap();
|
||||
log::info!("init glium backend for kui");
|
||||
Self {
|
||||
program,
|
||||
buffer: BufferPair::new(facade)
|
||||
program: Program::from_source(facade, VERTEX_SHADER, FRAGMENT_SHADER, None).unwrap(),
|
||||
context: Rc::clone(facade.get_context()),
|
||||
font_texture: None,
|
||||
plan: vec![]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_draw_plan(&mut self, plan: &UiDrawPlan) {
|
||||
assert!(plan.calls.len() == 1, "multiple draw calls not supported yet");
|
||||
let data_vtx = &plan.calls[0].vertices.iter().copied().map(Vertex::from).collect::<Vec<_>>();
|
||||
let data_idx = &plan.calls[0].indices;
|
||||
self.buffer.write_data(data_vtx, data_idx);
|
||||
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::<Vec<_>>()[..];
|
||||
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) {
|
||||
//HACK: get context from buffer
|
||||
let ctx = self.buffer.index_buffer.get_context();
|
||||
SrgbTexture2d::new(ctx, RawImage2d::from_raw_rgb(
|
||||
font_texture.data.to_owned(),
|
||||
(font_texture.size.x, font_texture.size.y)
|
||||
)).unwrap();
|
||||
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(plan) = kui.draw_plan().if_modified() {
|
||||
self.update_draw_plan(plan);
|
||||
}
|
||||
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) {
|
||||
if self.buffer.is_empty() {
|
||||
return
|
||||
}
|
||||
|
||||
let params = DrawParameters {
|
||||
blend: Blend::alpha_blending(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
frame.draw(
|
||||
self.buffer.vertex_buffer.slice(0..self.buffer.vertex_count).unwrap(),
|
||||
self.buffer.index_buffer.slice(0..self.buffer.index_count).unwrap(),
|
||||
&self.program,
|
||||
&uniform! {
|
||||
resolution: resolution.to_array(),
|
||||
},
|
||||
¶ms,
|
||||
).unwrap();
|
||||
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,
|
||||
&uniform! {
|
||||
resolution: resolution.to_array(),
|
||||
tex: bind_texture.as_ref(),
|
||||
use_tex: true,
|
||||
},
|
||||
¶ms,
|
||||
).unwrap();
|
||||
} else {
|
||||
frame.draw(
|
||||
vtx_buffer,
|
||||
idx_buffer,
|
||||
&self.program,
|
||||
&uniform! {
|
||||
resolution: resolution.to_array(),
|
||||
use_tex: false,
|
||||
},
|
||||
¶ms,
|
||||
).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
use crate::{IfModified, text::TextRenderer};
|
||||
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)]
|
||||
|
@ -23,6 +24,8 @@ pub enum UiDrawCommand {
|
|||
color: Vec4,
|
||||
///Text to draw
|
||||
text: Cow<'static, str>,
|
||||
///Font handle to use
|
||||
font: FontHandle,
|
||||
},
|
||||
}
|
||||
|
||||
|
@ -31,6 +34,12 @@ pub struct UiDrawCommands {
|
|||
pub commands: Vec<UiDrawCommand>,
|
||||
}
|
||||
|
||||
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 }
|
||||
|
@ -63,22 +72,74 @@ pub struct UiDrawPlan {
|
|||
pub calls: Vec<UiDrawCall>
|
||||
}
|
||||
|
||||
struct CallSwapper {
|
||||
calls: Vec<UiDrawCall>,
|
||||
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<UiDrawCall> {
|
||||
self.calls.push(self.call);
|
||||
self.calls
|
||||
}
|
||||
}
|
||||
|
||||
impl UiDrawPlan {
|
||||
pub fn build(calls: &UiDrawCommands, tr: &mut TextRenderer) -> Self {
|
||||
let mut call = UiDrawCall::default();
|
||||
for command in &calls.commands {
|
||||
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 idx = call.vertices.len() as u32;
|
||||
call.indices.extend([idx, idx + 1, idx + 2, idx, idx + 2, idx + 3]);
|
||||
call.vertices.extend([
|
||||
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::new(size.x, 0.0),
|
||||
position: *position + vec2(size.x, 0.0),
|
||||
color: *color,
|
||||
uv: vec2(1.0, 0.0),
|
||||
},
|
||||
|
@ -88,19 +149,60 @@ impl UiDrawPlan {
|
|||
uv: vec2(1.0, 1.0),
|
||||
},
|
||||
UiVertex {
|
||||
position: *position + Vec2::new(0.0, size.y),
|
||||
position: *position + vec2(0.0, size.y),
|
||||
color: *color,
|
||||
uv: vec2(0.0, 1.0),
|
||||
},
|
||||
]);
|
||||
},
|
||||
UiDrawCommand::Text { position, size, color, text } => {
|
||||
todo!()
|
||||
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 {
|
||||
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: vec![call]
|
||||
calls: swapper.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::any::Any;
|
||||
use crate::{
|
||||
LayoutInfo,
|
||||
draw::UiDrawCommand,
|
||||
draw::UiDrawCommands,
|
||||
measure::Response,
|
||||
state::StateRepo
|
||||
};
|
||||
|
@ -12,6 +12,7 @@ mod builtin {
|
|||
pub mod container;
|
||||
pub mod spacer;
|
||||
pub mod progress_bar;
|
||||
pub mod text;
|
||||
}
|
||||
|
||||
#[cfg(feature = "builtin_elements")]
|
||||
|
@ -24,5 +25,5 @@ pub trait UiElement {
|
|||
fn is_stateless(&self) -> bool { self.state_id().is_none() }
|
||||
fn init_state(&self) -> Option<Box<dyn Any>> { None }
|
||||
fn measure(&self, state: &StateRepo, layout: &LayoutInfo) -> Response;
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut Vec<UiDrawCommand>);
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands);
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ use crate::{
|
|||
UiDirection,
|
||||
UiSize,
|
||||
LayoutInfo,
|
||||
draw::UiDrawCommand,
|
||||
draw::{UiDrawCommand, UiDrawCommands},
|
||||
measure::{Response, Hints},
|
||||
state::StateRepo,
|
||||
element::UiElement
|
||||
|
@ -59,6 +59,7 @@ pub struct Container {
|
|||
//pub reverse: bool,
|
||||
pub gap: f32,
|
||||
pub padding: Sides<f32>,
|
||||
///Primary/secondary axis
|
||||
pub align: (Alignment, Alignment),
|
||||
pub background: Option<Vec4>,
|
||||
pub borders: Sides<Option<Border>>,
|
||||
|
@ -76,7 +77,6 @@ impl Default for Container {
|
|||
//reverse: false,
|
||||
gap: 0.,
|
||||
padding: Sides::all(0.),
|
||||
///Primary/secondary axis
|
||||
align: (Alignment::Begin, Alignment::Begin),
|
||||
background: Default::default(),
|
||||
borders: Default::default(),
|
||||
|
@ -150,12 +150,12 @@ impl UiElement for Container {
|
|||
}
|
||||
}
|
||||
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut Vec<UiDrawCommand>) {
|
||||
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.push(UiDrawCommand::Rectangle {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position,
|
||||
size: measure.size,
|
||||
color
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use glam::{vec2, Vec4, vec4};
|
||||
use crate::{
|
||||
UiSize, LayoutInfo,
|
||||
draw::UiDrawCommand,
|
||||
draw::{UiDrawCommand, UiDrawCommands},
|
||||
measure::Response,
|
||||
state::StateRepo,
|
||||
element::UiElement
|
||||
|
@ -50,17 +50,17 @@ impl UiElement for ProgressBar {
|
|||
}
|
||||
}
|
||||
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut Vec<UiDrawCommand>) {
|
||||
fn process(&self, measure: &Response, state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
let value = self.value.clamp(0., 1.);
|
||||
if value < 1. {
|
||||
draw.push(UiDrawCommand::Rectangle {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position: layout.position,
|
||||
size: measure.size,
|
||||
color: self.color_background
|
||||
});
|
||||
}
|
||||
if value > 0. {
|
||||
draw.push(UiDrawCommand::Rectangle {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position: layout.position,
|
||||
size: measure.size * vec2(value, 1.0),
|
||||
color: self.color_foreground
|
||||
|
|
|
@ -5,7 +5,7 @@ use crate::{
|
|||
element::UiElement,
|
||||
state::StateRepo,
|
||||
measure::Response,
|
||||
draw::UiDrawCommand
|
||||
draw::{UiDrawCommand, UiDrawCommands}
|
||||
};
|
||||
|
||||
pub struct Rect {
|
||||
|
@ -42,9 +42,9 @@ impl UiElement for Rect {
|
|||
}
|
||||
}
|
||||
|
||||
fn process(&self, measure: &Response, _state: &mut StateRepo, layout: &LayoutInfo, draw: &mut Vec<UiDrawCommand>) {
|
||||
fn process(&self, measure: &Response, _state: &mut StateRepo, layout: &LayoutInfo, draw: &mut UiDrawCommands) {
|
||||
if let Some(color) = self.color {
|
||||
draw.push(UiDrawCommand::Rectangle {
|
||||
draw.add(UiDrawCommand::Rectangle {
|
||||
position: layout.position,
|
||||
size: measure.size,
|
||||
color,
|
||||
|
|
|
@ -5,7 +5,7 @@ use crate::{
|
|||
element::UiElement,
|
||||
state::StateRepo,
|
||||
measure::Response,
|
||||
draw::UiDrawCommand
|
||||
draw::{UiDrawCommand, UiDrawCommands}
|
||||
};
|
||||
|
||||
pub struct Spacer(f32);
|
||||
|
@ -28,5 +28,5 @@ impl UiElement for Spacer {
|
|||
}
|
||||
}
|
||||
|
||||
fn process(&self, _measure: &Response, _state: &mut StateRepo, _layout: &LayoutInfo, _draw: &mut Vec<UiDrawCommand>) {}
|
||||
fn process(&self, _measure: &Response, _state: &mut StateRepo, _layout: &LayoutInfo, _draw: &mut UiDrawCommands) {}
|
||||
}
|
||||
|
|
59
kubi-ui/src/element/builtin/text.rs
Normal file
59
kubi-ui/src/element/builtin/text.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
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
|
||||
}
|
||||
|
||||
impl Default for Text {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: "".into(),
|
||||
size: (UiSize::Percentage(1.), UiSize::Pixels(32.)),
|
||||
color: Vec4::new(1., 1., 1., 1.),
|
||||
font: FontHandle(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 => 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) {
|
||||
draw.add(UiDrawCommand::Text {
|
||||
text: self.text.clone(),
|
||||
position: layout.position,
|
||||
size: 32,
|
||||
color: self.color,
|
||||
font: self.font
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
use crate::element::UiElement;
|
||||
use crate::{element::UiElement, draw::UiDrawCommands};
|
||||
|
||||
pub struct Interactable<T: UiElement> {
|
||||
pub element: T,
|
||||
|
@ -35,7 +35,7 @@ impl<T: UiElement> UiElement for Interactable<T> {
|
|||
self.element.measure(state, layout)
|
||||
}
|
||||
|
||||
fn process(&self, measure: &crate::measure::Response, state: &mut crate::state::StateRepo, layout: &crate::LayoutInfo, draw: &mut Vec<crate::draw::UiDrawCommand>) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,3 @@
|
|||
use std::collections::VecDeque;
|
||||
use glam::Vec2;
|
||||
|
||||
pub mod element;
|
||||
|
@ -11,9 +10,8 @@ pub mod interaction;
|
|||
|
||||
use element::UiElement;
|
||||
use state::StateRepo;
|
||||
use event::UiEvent;
|
||||
use draw::{UiDrawCommands, UiDrawPlan};
|
||||
use text::{TextRenderer, FontTextureInfo};
|
||||
use text::{TextRenderer, FontTextureInfo, FontHandle};
|
||||
|
||||
// pub struct ElementContext<'a> {
|
||||
// pub state: &'a mut StateRepo,
|
||||
|
@ -51,6 +49,10 @@ impl KubiUi {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn add_font_from_bytes(&mut self, font: &[u8]) -> FontHandle {
|
||||
self.text_renderer.add_font_from_bytes(font)
|
||||
}
|
||||
|
||||
pub fn add<T: UiElement>(&mut self, element: T, max_size: Vec2) {
|
||||
let layout = LayoutInfo {
|
||||
position: Vec2::ZERO,
|
||||
|
@ -58,7 +60,7 @@ impl KubiUi {
|
|||
direction: UiDirection::Vertical,
|
||||
};
|
||||
let measure = element.measure(&self.stateful_state, &layout);
|
||||
element.process(&measure, &mut self.stateful_state, &layout, &mut self.draw_commands.commands);
|
||||
element.process(&measure, &mut self.stateful_state, &layout, &mut self.draw_commands);
|
||||
}
|
||||
|
||||
pub fn begin(&mut self) {
|
||||
|
|
|
@ -1,12 +1,13 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
mod font;
|
||||
mod texman;
|
||||
mod ftm;
|
||||
|
||||
use font::FontManager;
|
||||
pub use font::FontHandle;
|
||||
use texman::FontTextureManager;
|
||||
pub use texman::{FontTextureInfo, GlyphCacheEntry};
|
||||
use fontdue::{Font, FontSettings};
|
||||
use ftm::FontTextureManager;
|
||||
pub use ftm::{FontTextureInfo, GlyphCacheEntry};
|
||||
|
||||
pub struct TextRenderer {
|
||||
fm: FontManager,
|
||||
|
@ -21,6 +22,10 @@ impl TextRenderer {
|
|||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
@ -32,6 +37,10 @@ impl TextRenderer {
|
|||
pub fn glyph(&mut self, font_handle: FontHandle, character: char, size: u8) -> Arc<GlyphCacheEntry> {
|
||||
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 {
|
||||
|
|
|
@ -3,7 +3,7 @@ use fontdue::Font;
|
|||
#[cfg(feature = "builtin_font")]
|
||||
const BIN_FONT: &[u8] = include_bytes!("../../assets/font/ProggyTiny.ttf");
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct FontHandle(pub(crate) usize);
|
||||
|
||||
#[cfg(feature = "builtin_font")]
|
||||
|
|
|
@ -60,7 +60,7 @@ impl FontTextureManager {
|
|||
FontTextureManager {
|
||||
glyph_cache: HashMap::new(),
|
||||
packer: DensePacker::new(size.x as i32, size.y as i32),
|
||||
font_texture: vec![0; (size.x * size.y) as usize],
|
||||
font_texture: vec![0; (size.x * size.y * 4) as usize],
|
||||
font_texture_size: size,
|
||||
modified: false,
|
||||
}
|
||||
|
@ -79,17 +79,18 @@ impl FontTextureManager {
|
|||
}
|
||||
|
||||
/// Either looks up the glyph in the cache or renders it and adds it to the cache.
|
||||
fn glyph_allocate(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> (bool, Arc<GlyphCacheEntry>) {
|
||||
pub fn glyph(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> Arc<GlyphCacheEntry> {
|
||||
let key = GlyphCacheKey {
|
||||
font_index: font_handle.0,
|
||||
character,
|
||||
size,
|
||||
};
|
||||
if let Some(entry) = self.glyph_cache.get(&key) {
|
||||
return (false, Arc::clone(entry));
|
||||
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 {
|
||||
|
@ -99,34 +100,40 @@ impl FontTextureManager {
|
|||
size: texture_size,
|
||||
});
|
||||
self.glyph_cache.insert_unique_unchecked(key, Arc::clone(&entry));
|
||||
(true, 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, .. } = entry;
|
||||
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;
|
||||
self.font_texture[dst] = entry.data[src];
|
||||
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<GlyphCacheEntry> {
|
||||
let (is_new, glyph) = self.glyph_allocate(font_manager, font_handle, character, size);
|
||||
if is_new {
|
||||
self.glyph_place(&glyph);
|
||||
self.modified = true;
|
||||
}
|
||||
glyph
|
||||
}
|
||||
// pub fn glyph(&mut self, font_manager: &FontManager, font_handle: FontHandle, character: char, size: u8) -> Arc<GlyphCacheEntry> {
|
||||
// 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(2048, 2048))
|
||||
Self::new(uvec2(1024, 1024))
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue