Initial commit
This commit is contained in:
parent
39865e05d3
commit
f5648e0f94
11 changed files with 2522 additions and 12 deletions
12
.gitignore
vendored
12
.gitignore
vendored
|
@ -1,10 +1,2 @@
|
||||||
# Generated by Cargo
|
/target
|
||||||
# will have compiled files and executables
|
.vscode
|
||||||
/target/
|
|
||||||
|
|
||||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
|
||||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
|
||||||
Cargo.lock
|
|
||||||
|
|
||||||
# These are backup files generated by rustfmt
|
|
||||||
**/*.rs.bk
|
|
||||||
|
|
1455
Cargo.lock
generated
Normal file
1455
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
17
Cargo.toml
Normal file
17
Cargo.toml
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
[package]
|
||||||
|
name = "glyphon"
|
||||||
|
description = "Fast, simple 2D text rendering for wgpu"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
homepage = "https://github.com/grovesNL/glyphon.git"
|
||||||
|
repository = "https://github.com/grovesNL/glyphon"
|
||||||
|
license = "MIT OR Apache-2.0 OR Zlib"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
wgpu = { git = "https://github.com/gfx-rs/wgpu/" }
|
||||||
|
fontdue = "0.7.2"
|
||||||
|
etagere = "0.2.6"
|
||||||
|
pollster = "0.2.5"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
winit = "0.26.1"
|
201
LICENSE-APACHE
Normal file
201
LICENSE-APACHE
Normal file
|
@ -0,0 +1,201 @@
|
||||||
|
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.
|
23
LICENSE-MIT
Normal file
23
LICENSE-MIT
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
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.
|
15
LICENSE-ZLIB
Normal file
15
LICENSE-ZLIB
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
This software is provided 'as-is', without any express or implied
|
||||||
|
warranty. In no event will the authors be held liable for any damages
|
||||||
|
arising from the use of this software.
|
||||||
|
|
||||||
|
Permission is granted to anyone to use this software for any purpose,
|
||||||
|
including commercial applications, and to alter it and redistribute it
|
||||||
|
freely, subject to the following restrictions:
|
||||||
|
|
||||||
|
1. The origin of this software must not be misrepresented; you must not
|
||||||
|
claim that you wrote the original software. If you use this software
|
||||||
|
in a product, an acknowledgment in the product documentation would be
|
||||||
|
appreciated but is not required.
|
||||||
|
2. Altered source versions must be plainly marked as such, and must not be
|
||||||
|
misrepresented as being the original software.
|
||||||
|
3. This notice may not be removed or altered from any source distribution.
|
34
README.md
34
README.md
|
@ -1,2 +1,32 @@
|
||||||
# glyphon
|
<h1 align="center">
|
||||||
🦅🦁 Fast, simple 2D text rendering for wgpu
|
🦅🦁 glyphon
|
||||||
|
</h1>
|
||||||
|
<div align="center">
|
||||||
|
Fast, simple 2D text rendering for wgpu
|
||||||
|
</div>
|
||||||
|
<br />
|
||||||
|
<div align="center">
|
||||||
|
<img src="https://img.shields.io/badge/Min%20Rust-1.54-green.svg" alt="Minimum Rust Version">
|
||||||
|
<a href="https://crates.io/crates/glyphon"><img src="https://img.shields.io/crates/v/glow.svg?label=glyphon" alt="crates.io"></a>
|
||||||
|
<a href="https://docs.rs/glyphon"><img src="https://docs.rs/glyphon/badge.svg" alt="docs.rs"></a>
|
||||||
|
<a href="https://github.com/grovesNL/glyphon/actions"><img src="https://github.com/grovesNL/glyphon/workflows/CI/badge.svg?branch=main" alt="Build Status" /></a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
## What is this?
|
||||||
|
|
||||||
|
This crate provides a simple way to render 2D text with [`wgpu`](https://github.com/gfx-rs/wgpu/) by:
|
||||||
|
|
||||||
|
- rasterizing glyphs (with [`fontdue`](https://github.com/mooman219/fontdue/))
|
||||||
|
- packing the glyphs into texture atlas (with [`etagere`](https://github.com/nical/etagere/))
|
||||||
|
- calculate layout for text (with [`fontdue`](https://github.com/mooman219/fontdue/))
|
||||||
|
- sampling from the texture atlas to render text (with [`wgpu`](https://github.com/gfx-rs/wgpu/))
|
||||||
|
|
||||||
|
To avoid extra render passes, rendering uses existing render passes(following the middleware pattern described in [`wgpu`'s Encapsulating Graphics Work wiki page](https://github.com/gfx-rs/wgpu/wiki/Encapsulating-Graphics-Work).
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under either [Apache License, Version 2.0](LICENSE-APACHE), [zlib License](LICENSE-ZLIB), or [MIT License](LICENSE-MIT), at your option.
|
||||||
|
|
||||||
|
## Contribution
|
||||||
|
|
||||||
|
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache 2.0 license, shall be triple licensed as above, without any additional terms or conditions.
|
||||||
|
|
BIN
examples/Inter-Bold.ttf
Normal file
BIN
examples/Inter-Bold.ttf
Normal file
Binary file not shown.
140
examples/hello-world.rs
Normal file
140
examples/hello-world.rs
Normal file
|
@ -0,0 +1,140 @@
|
||||||
|
use fontdue::{
|
||||||
|
layout::{CoordinateSystem, Layout, LayoutSettings, TextStyle},
|
||||||
|
Font, FontSettings,
|
||||||
|
};
|
||||||
|
use wgpu::{
|
||||||
|
Color, CommandEncoderDescriptor, LoadOp, Operations, RenderPassColorAttachment,
|
||||||
|
RenderPassDescriptor, TextureViewDescriptor,
|
||||||
|
};
|
||||||
|
use glyphon::{Resolution, TextRenderer};
|
||||||
|
use winit::{
|
||||||
|
event::{Event, WindowEvent},
|
||||||
|
event_loop::{ControlFlow, EventLoop},
|
||||||
|
window::Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
pollster::block_on(run());
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run() {
|
||||||
|
let instance = wgpu::Instance::new(wgpu::Backends::all());
|
||||||
|
let adapter = instance
|
||||||
|
.request_adapter(&wgpu::RequestAdapterOptions::default())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let (device, queue) = adapter
|
||||||
|
.request_device(
|
||||||
|
&wgpu::DeviceDescriptor {
|
||||||
|
label: None,
|
||||||
|
features: wgpu::Features::empty(),
|
||||||
|
limits: wgpu::Limits::downlevel_defaults(),
|
||||||
|
},
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let event_loop = EventLoop::new();
|
||||||
|
let window = Window::new(&event_loop).unwrap();
|
||||||
|
let surface = unsafe { instance.create_surface(&window) };
|
||||||
|
let size = window.inner_size();
|
||||||
|
let swapchain_format = surface.get_preferred_format(&adapter).unwrap();
|
||||||
|
let mut config = wgpu::SurfaceConfiguration {
|
||||||
|
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||||
|
format: swapchain_format,
|
||||||
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
present_mode: wgpu::PresentMode::Mailbox,
|
||||||
|
};
|
||||||
|
surface.configure(&device, &config);
|
||||||
|
|
||||||
|
let mut text_renderer = TextRenderer::new(
|
||||||
|
&device,
|
||||||
|
&queue,
|
||||||
|
swapchain_format,
|
||||||
|
Resolution {
|
||||||
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let font = include_bytes!("./Inter-Bold.ttf") as &[u8];
|
||||||
|
let font = Font::from_bytes(font, FontSettings::default()).unwrap();
|
||||||
|
let fonts = vec![font];
|
||||||
|
let mut layout = Layout::new(CoordinateSystem::PositiveYDown);
|
||||||
|
|
||||||
|
event_loop.run(move |event, _, control_flow| {
|
||||||
|
let _ = (&instance, &adapter);
|
||||||
|
|
||||||
|
*control_flow = ControlFlow::Poll;
|
||||||
|
match event {
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::Resized(size),
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
config.width = size.width;
|
||||||
|
config.height = size.height;
|
||||||
|
surface.configure(&device, &config);
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
Event::RedrawRequested(_) => {
|
||||||
|
layout.reset(&LayoutSettings {
|
||||||
|
x: 0.0,
|
||||||
|
y: 0.0,
|
||||||
|
..LayoutSettings::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
layout.append(
|
||||||
|
fonts.as_slice(),
|
||||||
|
&TextStyle::new("Hello world!\nI'm on a new line!", 50.0, 0),
|
||||||
|
);
|
||||||
|
|
||||||
|
text_renderer
|
||||||
|
.prepare(
|
||||||
|
&device,
|
||||||
|
&queue,
|
||||||
|
Resolution {
|
||||||
|
width: config.width,
|
||||||
|
height: config.height,
|
||||||
|
},
|
||||||
|
&fonts,
|
||||||
|
&[&layout],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let frame = surface.get_current_texture().unwrap();
|
||||||
|
let view = frame.texture.create_view(&TextureViewDescriptor::default());
|
||||||
|
let mut encoder =
|
||||||
|
device.create_command_encoder(&CommandEncoderDescriptor { label: None });
|
||||||
|
{
|
||||||
|
let mut pass = encoder.begin_render_pass(&RenderPassDescriptor {
|
||||||
|
label: None,
|
||||||
|
color_attachments: &[RenderPassColorAttachment {
|
||||||
|
view: &view,
|
||||||
|
resolve_target: None,
|
||||||
|
ops: Operations {
|
||||||
|
load: LoadOp::Clear(Color::BLACK),
|
||||||
|
store: true,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
depth_stencil_attachment: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
text_renderer.render(&mut pass).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
queue.submit(Some(encoder.finish()));
|
||||||
|
frame.present();
|
||||||
|
}
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::CloseRequested,
|
||||||
|
..
|
||||||
|
} => *control_flow = ControlFlow::Exit,
|
||||||
|
Event::MainEventsCleared => {
|
||||||
|
window.request_redraw();
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
566
src/lib.rs
Normal file
566
src/lib.rs
Normal file
|
@ -0,0 +1,566 @@
|
||||||
|
use std::{
|
||||||
|
borrow::Cow,
|
||||||
|
collections::{HashMap, HashSet},
|
||||||
|
error::Error,
|
||||||
|
fmt::{self, Display, Formatter},
|
||||||
|
iter, mem,
|
||||||
|
num::{NonZeroU32, NonZeroU64},
|
||||||
|
slice,
|
||||||
|
};
|
||||||
|
|
||||||
|
use etagere::{size2, AllocId, Allocation, BucketedAtlasAllocator};
|
||||||
|
use fontdue::{
|
||||||
|
layout::{GlyphRasterConfig, Layout},
|
||||||
|
Font,
|
||||||
|
};
|
||||||
|
use wgpu::{
|
||||||
|
util::{BufferInitDescriptor, DeviceExt},
|
||||||
|
BindGroup, BindGroupEntry, BindGroupLayoutEntry, BindingResource, BindingType, BlendState,
|
||||||
|
Buffer, BufferBindingType, BufferDescriptor, BufferUsages, ColorTargetState, ColorWrites,
|
||||||
|
Device, Extent3d, FilterMode, FragmentState, ImageCopyTexture, ImageDataLayout, IndexFormat,
|
||||||
|
MultisampleState, Origin3d, PipelineLayoutDescriptor, PrimitiveState, Queue, RenderPass,
|
||||||
|
RenderPipeline, RenderPipelineDescriptor, SamplerBindingType, SamplerDescriptor,
|
||||||
|
ShaderModuleDescriptor, ShaderSource, ShaderStages, Texture, TextureAspect, TextureDescriptor,
|
||||||
|
TextureDimension, TextureFormat, TextureSampleType, TextureUsages, TextureViewDescriptor,
|
||||||
|
TextureViewDimension, VertexFormat, VertexState,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub enum PrepareError {
|
||||||
|
AtlasFull,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for PrepareError {
|
||||||
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
|
write!(f, "prepare error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for PrepareError {}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub enum RenderError {}
|
||||||
|
|
||||||
|
impl Display for RenderError {
|
||||||
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
|
write!(f, "render error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum GpuCache {
|
||||||
|
InAtlas { x: u16, y: u16 },
|
||||||
|
SkipRasterization,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GlyphDetails {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
gpu_cache: GpuCache,
|
||||||
|
atlas_id: Option<AllocId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct GlyphToRender {
|
||||||
|
x: f32,
|
||||||
|
y: f32,
|
||||||
|
width: f32,
|
||||||
|
height: f32,
|
||||||
|
atlas_x: f32,
|
||||||
|
atlas_y: f32,
|
||||||
|
color: [u8; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub struct Resolution {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub struct Params {
|
||||||
|
screen_resolution: Resolution,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_allocate(
|
||||||
|
atlas_packer: &mut BucketedAtlasAllocator,
|
||||||
|
layout: &Layout,
|
||||||
|
glyph_cache: &mut HashMap<GlyphRasterConfig, GlyphDetails>,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
) -> Option<Allocation> {
|
||||||
|
let size = size2(width as i32, height as i32);
|
||||||
|
let allocation = atlas_packer.allocate(size);
|
||||||
|
|
||||||
|
if allocation.is_some() {
|
||||||
|
return allocation;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to free any allocations not used in the current layout
|
||||||
|
let used_glyphs = layout
|
||||||
|
.glyphs()
|
||||||
|
.iter()
|
||||||
|
.map(|gp| gp.key)
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
|
||||||
|
glyph_cache.retain(|key, details| {
|
||||||
|
if used_glyphs.contains(&key) {
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
if let Some(atlas_id) = details.atlas_id {
|
||||||
|
atlas_packer.deallocate(atlas_id)
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Attempt to reallocate
|
||||||
|
atlas_packer.allocate(size)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TextRenderer {
|
||||||
|
glyph_cache: HashMap<GlyphRasterConfig, GlyphDetails>,
|
||||||
|
atlas_texture_pending: Vec<u8>,
|
||||||
|
atlas_texture: Texture,
|
||||||
|
atlas_packer: BucketedAtlasAllocator,
|
||||||
|
atlas_width: u32,
|
||||||
|
atlas_height: u32,
|
||||||
|
pipeline: RenderPipeline,
|
||||||
|
vertex_buffer: Buffer,
|
||||||
|
vertex_buffer_size: u64,
|
||||||
|
index_buffer: Buffer,
|
||||||
|
index_buffer_size: u64,
|
||||||
|
params: Params,
|
||||||
|
params_buffer: Buffer,
|
||||||
|
bind_group: BindGroup,
|
||||||
|
vertices_to_render: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TextRenderer {
|
||||||
|
pub fn new(
|
||||||
|
device: &Device,
|
||||||
|
_queue: &Queue,
|
||||||
|
format: TextureFormat,
|
||||||
|
screen_resolution: Resolution,
|
||||||
|
) -> Self {
|
||||||
|
let glyph_cache = HashMap::new();
|
||||||
|
let max_texture_dimension_2d = device.limits().max_texture_dimension_2d;
|
||||||
|
let atlas_width = max_texture_dimension_2d;
|
||||||
|
let atlas_height = max_texture_dimension_2d;
|
||||||
|
|
||||||
|
let atlas_packer =
|
||||||
|
BucketedAtlasAllocator::new(size2(atlas_width as i32, atlas_height as i32));
|
||||||
|
|
||||||
|
// Create a texture to use for our atlas
|
||||||
|
let atlas_texture_pending = vec![0; (atlas_width * atlas_height) as usize];
|
||||||
|
let atlas_texture = device.create_texture(&TextureDescriptor {
|
||||||
|
label: Some("glyphon atlas"),
|
||||||
|
size: Extent3d {
|
||||||
|
width: atlas_width,
|
||||||
|
height: atlas_height,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
},
|
||||||
|
mip_level_count: 1,
|
||||||
|
sample_count: 1,
|
||||||
|
dimension: TextureDimension::D2,
|
||||||
|
format: TextureFormat::R8Unorm,
|
||||||
|
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
let atlas_texture_view = atlas_texture.create_view(&TextureViewDescriptor::default());
|
||||||
|
let atlas_sampler = device.create_sampler(&SamplerDescriptor {
|
||||||
|
label: Some("glyphon sampler"),
|
||||||
|
min_filter: FilterMode::Nearest,
|
||||||
|
mag_filter: FilterMode::Nearest,
|
||||||
|
mipmap_filter: FilterMode::Nearest,
|
||||||
|
lod_min_clamp: 0f32,
|
||||||
|
lod_max_clamp: 0f32,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a render pipeline to use for rendering later
|
||||||
|
let shader = device.create_shader_module(&ShaderModuleDescriptor {
|
||||||
|
label: Some("glyphon shader"),
|
||||||
|
source: ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||||
|
});
|
||||||
|
|
||||||
|
let vertex_buffers = [wgpu::VertexBufferLayout {
|
||||||
|
array_stride: mem::size_of::<GlyphToRender>() as wgpu::BufferAddress,
|
||||||
|
step_mode: wgpu::VertexStepMode::Vertex,
|
||||||
|
attributes: &[
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
format: VertexFormat::Float32x4,
|
||||||
|
offset: 0,
|
||||||
|
shader_location: 0,
|
||||||
|
},
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
format: VertexFormat::Float32x2,
|
||||||
|
offset: mem::size_of::<f32>() as u64 * 4,
|
||||||
|
shader_location: 1,
|
||||||
|
},
|
||||||
|
wgpu::VertexAttribute {
|
||||||
|
format: VertexFormat::Uint32,
|
||||||
|
offset: mem::size_of::<f32>() as u64 * 6,
|
||||||
|
shader_location: 2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}];
|
||||||
|
|
||||||
|
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
|
entries: &[
|
||||||
|
BindGroupLayoutEntry {
|
||||||
|
binding: 0,
|
||||||
|
visibility: ShaderStages::VERTEX,
|
||||||
|
ty: BindingType::Buffer {
|
||||||
|
ty: BufferBindingType::Uniform,
|
||||||
|
has_dynamic_offset: false,
|
||||||
|
min_binding_size: NonZeroU64::new(mem::size_of::<Params>() as u64),
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
BindGroupLayoutEntry {
|
||||||
|
binding: 1,
|
||||||
|
visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
|
||||||
|
ty: BindingType::Texture {
|
||||||
|
multisampled: false,
|
||||||
|
view_dimension: TextureViewDimension::D2,
|
||||||
|
sample_type: TextureSampleType::Float { filterable: true },
|
||||||
|
},
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
BindGroupLayoutEntry {
|
||||||
|
binding: 2,
|
||||||
|
visibility: ShaderStages::FRAGMENT,
|
||||||
|
ty: BindingType::Sampler(SamplerBindingType::Filtering),
|
||||||
|
count: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: Some("glyphon bind group layout"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let params = Params { screen_resolution };
|
||||||
|
|
||||||
|
let params_raw = unsafe {
|
||||||
|
slice::from_raw_parts(
|
||||||
|
¶ms as *const Params as *const u8,
|
||||||
|
mem::size_of::<Params>(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let params_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
|
label: Some("glyphon params"),
|
||||||
|
contents: params_raw,
|
||||||
|
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
|
||||||
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
|
layout: &bind_group_layout,
|
||||||
|
entries: &[
|
||||||
|
BindGroupEntry {
|
||||||
|
binding: 0,
|
||||||
|
resource: params_buffer.as_entire_binding(),
|
||||||
|
},
|
||||||
|
BindGroupEntry {
|
||||||
|
binding: 1,
|
||||||
|
resource: BindingResource::TextureView(&atlas_texture_view),
|
||||||
|
},
|
||||||
|
BindGroupEntry {
|
||||||
|
binding: 2,
|
||||||
|
resource: BindingResource::Sampler(&atlas_sampler),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
label: Some("glyphon bind group"),
|
||||||
|
});
|
||||||
|
|
||||||
|
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
|
||||||
|
label: None,
|
||||||
|
bind_group_layouts: &[&bind_group_layout],
|
||||||
|
push_constant_ranges: &[],
|
||||||
|
});
|
||||||
|
|
||||||
|
let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
|
||||||
|
label: Some("glyphon pipeline"),
|
||||||
|
layout: Some(&pipeline_layout),
|
||||||
|
vertex: VertexState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "vs_main",
|
||||||
|
buffers: &vertex_buffers,
|
||||||
|
},
|
||||||
|
fragment: Some(FragmentState {
|
||||||
|
module: &shader,
|
||||||
|
entry_point: "fs_main",
|
||||||
|
targets: &[ColorTargetState {
|
||||||
|
format,
|
||||||
|
blend: Some(BlendState::ALPHA_BLENDING),
|
||||||
|
write_mask: ColorWrites::default(),
|
||||||
|
}],
|
||||||
|
}),
|
||||||
|
primitive: PrimitiveState::default(),
|
||||||
|
depth_stencil: None,
|
||||||
|
multisample: MultisampleState {
|
||||||
|
count: 1,
|
||||||
|
mask: !0,
|
||||||
|
alpha_to_coverage_enabled: false,
|
||||||
|
},
|
||||||
|
multiview: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
let vertex_buffer_size = 4096;
|
||||||
|
let vertex_buffer = device.create_buffer(&BufferDescriptor {
|
||||||
|
label: Some("glyphon vertices"),
|
||||||
|
size: vertex_buffer_size,
|
||||||
|
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
|
||||||
|
mapped_at_creation: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
let index_buffer_size = 4096;
|
||||||
|
let index_buffer = device.create_buffer(&BufferDescriptor {
|
||||||
|
label: Some("glyphon indices"),
|
||||||
|
size: index_buffer_size,
|
||||||
|
usage: BufferUsages::INDEX | BufferUsages::COPY_DST,
|
||||||
|
mapped_at_creation: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
|
glyph_cache,
|
||||||
|
atlas_texture_pending,
|
||||||
|
atlas_texture,
|
||||||
|
atlas_packer,
|
||||||
|
atlas_width,
|
||||||
|
atlas_height,
|
||||||
|
pipeline,
|
||||||
|
vertex_buffer,
|
||||||
|
vertex_buffer_size,
|
||||||
|
index_buffer,
|
||||||
|
index_buffer_size,
|
||||||
|
params,
|
||||||
|
params_buffer,
|
||||||
|
bind_group,
|
||||||
|
vertices_to_render: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare(
|
||||||
|
&mut self,
|
||||||
|
device: &Device,
|
||||||
|
queue: &Queue,
|
||||||
|
screen_resolution: Resolution,
|
||||||
|
fonts: &[Font],
|
||||||
|
layouts: &[&Layout],
|
||||||
|
) -> Result<(), PrepareError> {
|
||||||
|
if screen_resolution != self.params.screen_resolution {
|
||||||
|
self.params.screen_resolution = screen_resolution;
|
||||||
|
queue.write_buffer(&self.params_buffer, 0, unsafe {
|
||||||
|
slice::from_raw_parts(
|
||||||
|
&self.params as *const Params as *const u8,
|
||||||
|
mem::size_of::<Params>(),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UploadBounds {
|
||||||
|
x_min: usize,
|
||||||
|
x_max: usize,
|
||||||
|
y_min: usize,
|
||||||
|
y_max: usize,
|
||||||
|
}
|
||||||
|
let mut upload_bounds = None::<UploadBounds>;
|
||||||
|
|
||||||
|
for layout in layouts.iter() {
|
||||||
|
for glyph in layout.glyphs() {
|
||||||
|
let already_on_gpu = self.glyph_cache.contains_key(&glyph.key);
|
||||||
|
if already_on_gpu {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let font = &fonts[glyph.font_index];
|
||||||
|
let (metrics, bitmap) = font.rasterize_config(glyph.key);
|
||||||
|
|
||||||
|
let (gpu_cache, atlas_id) = if glyph.char_data.rasterize() {
|
||||||
|
// Find a position in the packer
|
||||||
|
let allocation = match try_allocate(
|
||||||
|
&mut self.atlas_packer,
|
||||||
|
layout,
|
||||||
|
&mut self.glyph_cache,
|
||||||
|
metrics.width,
|
||||||
|
metrics.height,
|
||||||
|
) {
|
||||||
|
Some(a) => a,
|
||||||
|
None => return Err(PrepareError::AtlasFull),
|
||||||
|
};
|
||||||
|
let atlas_min = allocation.rectangle.min;
|
||||||
|
let atlas_max = allocation.rectangle.max;
|
||||||
|
|
||||||
|
for row in 0..metrics.height {
|
||||||
|
let y_offset = atlas_min.y as usize;
|
||||||
|
let x_offset =
|
||||||
|
(y_offset + row) * self.atlas_width as usize + atlas_min.x as usize;
|
||||||
|
let bitmap_row = &bitmap[row * metrics.width..(row + 1) * metrics.width];
|
||||||
|
self.atlas_texture_pending[x_offset..x_offset + metrics.width]
|
||||||
|
.copy_from_slice(bitmap_row);
|
||||||
|
}
|
||||||
|
|
||||||
|
match upload_bounds.as_mut() {
|
||||||
|
Some(ub) => {
|
||||||
|
ub.x_min = ub.x_min.min(atlas_min.x as usize);
|
||||||
|
ub.x_max = ub.x_max.max(atlas_max.x as usize);
|
||||||
|
ub.y_min = ub.y_min.min(atlas_min.y as usize);
|
||||||
|
ub.y_max = ub.y_max.max(atlas_max.y as usize);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
upload_bounds = Some(UploadBounds {
|
||||||
|
x_min: atlas_min.x as usize,
|
||||||
|
x_max: atlas_max.x as usize,
|
||||||
|
y_min: atlas_min.y as usize,
|
||||||
|
y_max: atlas_max.y as usize,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(
|
||||||
|
GpuCache::InAtlas {
|
||||||
|
x: atlas_min.x as u16,
|
||||||
|
y: atlas_min.y as u16,
|
||||||
|
},
|
||||||
|
Some(allocation.id),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(GpuCache::SkipRasterization, None)
|
||||||
|
};
|
||||||
|
|
||||||
|
self.glyph_cache.insert(
|
||||||
|
glyph.key,
|
||||||
|
GlyphDetails {
|
||||||
|
width: metrics.width as u32,
|
||||||
|
height: metrics.height as u32,
|
||||||
|
gpu_cache,
|
||||||
|
atlas_id,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(ub) = upload_bounds {
|
||||||
|
queue.write_texture(
|
||||||
|
ImageCopyTexture {
|
||||||
|
texture: &self.atlas_texture,
|
||||||
|
mip_level: 0,
|
||||||
|
origin: Origin3d {
|
||||||
|
x: ub.x_min as u32,
|
||||||
|
y: ub.y_min as u32,
|
||||||
|
z: 0,
|
||||||
|
},
|
||||||
|
aspect: TextureAspect::All,
|
||||||
|
},
|
||||||
|
&self.atlas_texture_pending[ub.y_min * self.atlas_width as usize + ub.x_min..],
|
||||||
|
ImageDataLayout {
|
||||||
|
offset: 0,
|
||||||
|
bytes_per_row: NonZeroU32::new(self.atlas_width as u32),
|
||||||
|
rows_per_image: NonZeroU32::new(self.atlas_height as u32),
|
||||||
|
},
|
||||||
|
Extent3d {
|
||||||
|
width: (ub.x_max - ub.x_min) as u32,
|
||||||
|
height: (ub.y_max - ub.y_min) as u32,
|
||||||
|
depth_or_array_layers: 1,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut glyph_vertices = Vec::new();
|
||||||
|
let mut glyph_indices = Vec::new();
|
||||||
|
let mut glyphs_added = 0;
|
||||||
|
|
||||||
|
for layout in layouts.iter() {
|
||||||
|
for glyph in layout.glyphs() {
|
||||||
|
let details = self.glyph_cache.get_mut(&glyph.key).unwrap();
|
||||||
|
let (atlas_x, atlas_y) = match details.gpu_cache {
|
||||||
|
GpuCache::InAtlas { x, y } => (x, y),
|
||||||
|
GpuCache::SkipRasterization => continue,
|
||||||
|
};
|
||||||
|
|
||||||
|
glyph_vertices.extend(
|
||||||
|
iter::repeat(GlyphToRender {
|
||||||
|
x: glyph.x,
|
||||||
|
y: glyph.y,
|
||||||
|
width: details.width as f32,
|
||||||
|
height: details.height as f32,
|
||||||
|
atlas_x: atlas_x as f32,
|
||||||
|
atlas_y: atlas_y as f32,
|
||||||
|
color: [255, 255, 0, 255],
|
||||||
|
})
|
||||||
|
.take(4),
|
||||||
|
);
|
||||||
|
|
||||||
|
let start = 4 * glyphs_added as u32;
|
||||||
|
glyph_indices.extend([start, start + 1, start + 2, start, start + 2, start + 3]);
|
||||||
|
|
||||||
|
glyphs_added += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const VERTICES_PER_GLYPH: u32 = 6;
|
||||||
|
self.vertices_to_render = glyphs_added as u32 * VERTICES_PER_GLYPH;
|
||||||
|
|
||||||
|
let will_render = glyphs_added > 0;
|
||||||
|
if !will_render {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let vertices = glyph_vertices.as_slice();
|
||||||
|
let vertices_raw = unsafe {
|
||||||
|
slice::from_raw_parts(
|
||||||
|
vertices as *const _ as *const u8,
|
||||||
|
mem::size_of::<GlyphToRender>() * vertices.len(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.vertex_buffer_size >= vertices_raw.len() as u64 {
|
||||||
|
queue.write_buffer(&self.vertex_buffer, 0, vertices_raw);
|
||||||
|
} else {
|
||||||
|
self.vertex_buffer.destroy();
|
||||||
|
self.vertex_buffer_size = vertices_raw.len().next_power_of_two() as u64;
|
||||||
|
self.vertex_buffer = device.create_buffer_init(&BufferInitDescriptor {
|
||||||
|
label: Some("glyphon vertices"),
|
||||||
|
contents: vertices_raw,
|
||||||
|
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let indices = glyph_indices.as_slice();
|
||||||
|
let indices_raw = unsafe {
|
||||||
|
slice::from_raw_parts(
|
||||||
|
indices as *const _ as *const u8,
|
||||||
|
mem::size_of::<u32>() * indices.len(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.index_buffer_size >= indices_raw.len() as u64 {
|
||||||
|
queue.write_buffer(&self.index_buffer, 0, indices_raw);
|
||||||
|
} else {
|
||||||
|
self.index_buffer.destroy();
|
||||||
|
self.index_buffer_size = indices_raw.len().next_power_of_two() as u64;
|
||||||
|
self.index_buffer = device.create_buffer_init(&BufferInitDescriptor {
|
||||||
|
label: Some("glyphon indices"),
|
||||||
|
contents: indices_raw,
|
||||||
|
usage: BufferUsages::INDEX | BufferUsages::COPY_DST,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render<'pass>(&'pass mut self, pass: &mut RenderPass<'pass>) -> Result<(), ()> {
|
||||||
|
if self.vertices_to_render == 0 {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
pass.set_pipeline(&self.pipeline);
|
||||||
|
pass.set_bind_group(0, &self.bind_group, &[]);
|
||||||
|
pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
||||||
|
pass.set_index_buffer(self.index_buffer.slice(..), IndexFormat::Uint32);
|
||||||
|
pass.draw_indexed(0..self.vertices_to_render, 0, 0..1);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
71
src/shader.wgsl
Normal file
71
src/shader.wgsl
Normal file
|
@ -0,0 +1,71 @@
|
||||||
|
struct VertexOutput {
|
||||||
|
@builtin(position) position: vec4<f32>,
|
||||||
|
@location(0) color: vec4<f32>,
|
||||||
|
@location(1) tex_coords: vec2<f32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Params {
|
||||||
|
screen_resolution: vec2<u32>,
|
||||||
|
};
|
||||||
|
|
||||||
|
@group(0) @binding(0)
|
||||||
|
var<uniform> params: Params;
|
||||||
|
|
||||||
|
@group(0) @binding(1)
|
||||||
|
var atlas_texture: texture_2d<f32>;
|
||||||
|
|
||||||
|
@group(0) @binding(2)
|
||||||
|
var atlas_sampler: sampler;
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_main(@builtin(vertex_index) vertex_idx: u32, @location(0) in_vert: vec4<f32>, @location(1) tex_coords: vec2<f32>, @location(2) color: u32) -> VertexOutput {
|
||||||
|
let width = in_vert.z;
|
||||||
|
let height = in_vert.w;
|
||||||
|
|
||||||
|
let v = vertex_idx % 4u;
|
||||||
|
var pos = in_vert.xy;
|
||||||
|
var uv = tex_coords;
|
||||||
|
|
||||||
|
switch v {
|
||||||
|
case 0u: {
|
||||||
|
}
|
||||||
|
case 1u: {
|
||||||
|
pos.x += width;
|
||||||
|
uv.x += width;
|
||||||
|
}
|
||||||
|
case 2u: {
|
||||||
|
pos.x += width;
|
||||||
|
pos.y += height;
|
||||||
|
uv.x += width;
|
||||||
|
uv.y += height;
|
||||||
|
}
|
||||||
|
case 3u: {
|
||||||
|
pos.y += height;
|
||||||
|
uv.y += height;
|
||||||
|
}
|
||||||
|
default: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
pos = 2.0 * pos / vec2<f32>(params.screen_resolution) - 1.0;
|
||||||
|
pos.y *= -1.0;
|
||||||
|
|
||||||
|
var vert_output: VertexOutput;
|
||||||
|
|
||||||
|
vert_output.position = vec4<f32>(pos.xy, 0.0, 1.0);
|
||||||
|
|
||||||
|
vert_output.color = vec4<f32>(
|
||||||
|
f32((color & 0xffu)),
|
||||||
|
f32((color & 0xff00u) >> 8u),
|
||||||
|
f32((color & 0xff0000u) >> 16u),
|
||||||
|
f32((color & 0xff000000u) >> 24u),
|
||||||
|
) / 255.0;
|
||||||
|
|
||||||
|
vert_output.tex_coords = uv / vec2<f32>(textureDimensions(atlas_texture).xy);
|
||||||
|
|
||||||
|
return vert_output;
|
||||||
|
}
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_main(in_frag: VertexOutput) -> @location(0) vec4<f32> {
|
||||||
|
return in_frag.color * textureSample(atlas_texture, atlas_sampler, in_frag.tex_coords).x;
|
||||||
|
}
|
Loading…
Reference in a new issue