Skip to content

Commit

Permalink
Provided example to reproduce hecrj#78
Browse files Browse the repository at this point in the history
  • Loading branch information
pacmancoder committed Oct 25, 2021
1 parent cd6f154 commit b61f425
Show file tree
Hide file tree
Showing 4 changed files with 113 additions and 26 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/target
**/*.rs.bk
Cargo.lock
Cargo.lock

*.wasm
*.js
17 changes: 15 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,28 @@ readme = "README.md"
resolver = "2"

[dependencies]
wgpu = "0.11"
wgpu = { version = "0.11", features = ["webgl"] }
glyph_brush = "0.7"
log = "0.4"

# Deep in the dependency tree (glyph-brush/twox-hash/rand/rand_chacha/getrandom)
# this thing breaks on `wasm32-unknown-unkwnown`... This dependency here is
# only to make it compile (cargo always selects crate configuration with the
# broadest feature set), not yet figured out how to make more robust workarround
getrandom = { version = "0.2.3", features = ["js"] }

[dependencies.bytemuck]
version = "1.4"
features = ["derive"]

[dev-dependencies]
env_logger = "0.7"
winit = "0.24"
winit = { version = "0.24", features = ["web-sys"] }
futures = "0.3"

[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
console_error_panic_hook = "0.1.7"
console_log = "0.2.0"
log = "0.4"
wasm-bindgen = "0.2"
web-sys = { version = "0.3.27", features = ["Element", "HtmlCanvasElement", "Window", "Document"] }
97 changes: 74 additions & 23 deletions examples/hello.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,81 @@
use std::error::Error;
use wgpu_glyph::{ab_glyph, GlyphBrushBuilder, Section, Text};

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast;
#[cfg(target_arch = "wasm32")]
use web_sys::HtmlCanvasElement;
#[cfg(target_arch = "wasm32")]
use winit::platform::web::WindowBuilderExtWebSys;

fn main() -> Result<(), Box<dyn Error>> {
#[cfg(target_arch = "wasm32")]
let canvas_element = {
console_log::init_with_level(log::Level::Debug)
.expect("could not initialize logger");
std::panic::set_hook(Box::new(console_error_panic_hook::hook));

web_sys::window()
.and_then(|win| win.document())
.and_then(|doc| doc.get_element_by_id("iced_canvas"))
.and_then(|element| element.dyn_into::<HtmlCanvasElement>().ok())
.expect("Canvas with id `iced_canvas` is missing")
};

#[cfg(not(target_arch = "wasm32"))]
env_logger::init();

// Open window and create a surface
let event_loop = winit::event_loop::EventLoop::new();

#[cfg(target_arch = "wasm32")]
let window = winit::window::WindowBuilder::new()
.with_resizable(false)
.with_canvas(Some(canvas_element))
.build(&event_loop)
.unwrap();
.expect("Failed to build winit window");

#[cfg(not(target_arch = "wasm32"))]
let window = winit::window::WindowBuilder::new()
.with_resizable(false)
.build(&event_loop)
.expect("Failed to build winit window");

let backend =
wgpu::util::backend_bits_from_env().unwrap_or(wgpu::Backends::GL);

let instance = wgpu::Instance::new(backend);

let instance = wgpu::Instance::new(wgpu::Backends::all());
let surface = unsafe { instance.create_surface(&window) };

// Initialize GPU
let (device, queue) = futures::executor::block_on(async {
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
let (render_format, (device, queue)) = futures::executor::block_on(async {
let adapter = wgpu::util::initialize_adapter_from_env_or_default(
&instance,
backend,
Some(&surface),
)
.await
.expect("No suitable GPU adapters found on the system!");

let adapter_features = adapter.features();

let needed_limits = wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits());

let format = surface
.get_preferred_format(&adapter)
.expect("Get preferred format");

let device = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
features: adapter_features & wgpu::Features::default(),
limits: needed_limits,
}, None)
.await
.expect("Request adapter");
.expect("Request device");

adapter
.request_device(&wgpu::DeviceDescriptor::default(), None)
.await
.expect("Request device")
(format, device)
});

// Create staging belt and a local pool
Expand All @@ -38,9 +84,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let local_spawner = local_pool.spawner();

// Prepare swap chain
let render_format = wgpu::TextureFormat::Bgra8UnormSrgb;
let mut size = window.inner_size();

surface.configure(
&device,
&wgpu::SurfaceConfiguration {
Expand All @@ -57,14 +101,19 @@ fn main() -> Result<(), Box<dyn Error>> {
"Inconsolata-Regular.ttf"
))?;

let mut glyph_brush = GlyphBrushBuilder::using_font(inconsolata)
.build(&device, render_format);
let glyph_builder = GlyphBrushBuilder::using_font(inconsolata)
.draw_cache_align_4x4(true);

let mut glyph_brush = glyph_builder.build(&device, render_format);

// Render loop
window.request_redraw();
let mut counter = 0usize;

event_loop.run(move |event, _, control_flow| {
match event {
winit::event::Event::NewEvents(winit::event::StartCause::Poll) => {
window.request_redraw();
*control_flow = winit::event_loop::ControlFlow::Poll;
}
winit::event::Event::WindowEvent {
event: winit::event::WindowEvent::CloseRequested,
..
Expand Down Expand Up @@ -131,12 +180,14 @@ fn main() -> Result<(), Box<dyn Error>> {
glyph_brush.queue(Section {
screen_position: (30.0, 30.0),
bounds: (size.width as f32, size.height as f32),
text: vec![Text::new("Hello wgpu_glyph!")
text: vec![Text::new(&format!("Frame #{}!", counter))
.with_color([0.0, 0.0, 0.0, 1.0])
.with_scale(40.0)],
..Section::default()
});

counter = counter.wrapping_add(1);

glyph_brush.queue(Section {
screen_position: (30.0, 90.0),
bounds: (size.width as f32, size.height as f32),
Expand Down Expand Up @@ -172,7 +223,7 @@ fn main() -> Result<(), Box<dyn Error>> {
local_pool.run_until_stalled();
}
_ => {
*control_flow = winit::event_loop::ControlFlow::Wait;
*control_flow = winit::event_loop::ControlFlow::Poll;
}
}
})
Expand Down
20 changes: 20 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>wgpu_glyph hello</title>
</head>
<body>
<canvas id="iced_canvas"></canvas>
<script type="module">
import init from "./hello.js";
init('./hello_bg.wasm');
</script>
<style>
body {
width: 100%;
text-align: center;
}
</style>
</body>
</html>

0 comments on commit b61f425

Please sign in to comment.