| 1 |
//! This example shows interop with raw GLES contexts - |
| 2 |
//! the ability to hook up wgpu-hal to an existing context and draw into it. |
| 3 |
//! |
| 4 |
//! Emscripten build: |
| 5 |
//! 1. install emsdk |
| 6 |
//! 2. build this example with cargo: |
| 7 |
//! EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" cargo build --example raw-gles --target wasm32-unknown-emscripten |
| 8 |
//! 3. copy raw-gles.em.html into target directory and open it in browser: |
| 9 |
//! cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples |
| 10 |
|
| 11 |
extern crate wgpu_hal as hal; |
| 12 |
|
| 13 |
#[cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos")))] |
| 14 |
fn main() { |
| 15 |
use std::{ffi::CString, num::NonZeroU32}; |
| 16 |
|
| 17 |
use glutin::{ |
| 18 |
config::GlConfig as _, |
| 19 |
context::{NotCurrentGlContext as _, PossiblyCurrentGlContext as _, Version}, |
| 20 |
display::{GetGlDisplay as _, GlDisplay as _}, |
| 21 |
surface::GlSurface as _, |
| 22 |
}; |
| 23 |
use glutin_winit::GlWindow as _; |
| 24 |
use rwh_05::HasRawWindowHandle as _; |
| 25 |
|
| 26 |
env_logger::init(); |
| 27 |
println!("Initializing external GL context"); |
| 28 |
|
| 29 |
let event_loop = winit::event_loop::EventLoop::new().unwrap(); |
| 30 |
// Only Windows requires the window to be present before creating the display. |
| 31 |
// Other platforms don't really need one. |
| 32 |
let window_builder = cfg!(windows).then(|| { |
| 33 |
winit::window::WindowBuilder::new() |
| 34 |
.with_title("WGPU raw GLES example (press Escape to exit)") |
| 35 |
}); |
| 36 |
|
| 37 |
// The template will match only the configurations supporting rendering |
| 38 |
// to Windows. |
| 39 |
let template = glutin::config::ConfigTemplateBuilder::new(); |
| 40 |
|
| 41 |
let display_builder = glutin_winit::DisplayBuilder::new().with_window_builder(window_builder); |
| 42 |
|
| 43 |
// Find the config with the maximum number of samples, so our triangle will be |
| 44 |
// smooth. |
| 45 |
pub fn gl_config_picker( |
| 46 |
configs: Box<dyn Iterator<Item = glutin::config::Config> + '_>, |
| 47 |
) -> glutin::config::Config { |
| 48 |
configs |
| 49 |
.reduce(|accum, config| { |
| 50 |
if config.num_samples() > accum.num_samples() { |
| 51 |
config |
| 52 |
} else { |
| 53 |
accum |
| 54 |
} |
| 55 |
}) |
| 56 |
.expect("Failed to find a matching config") |
| 57 |
} |
| 58 |
|
| 59 |
let (mut window, gl_config) = display_builder |
| 60 |
.build(&event_loop, template, gl_config_picker) |
| 61 |
.expect("Failed to build window and config from display"); |
| 62 |
|
| 63 |
println!("Picked a config with {} samples", gl_config.num_samples()); |
| 64 |
|
| 65 |
let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle()); |
| 66 |
|
| 67 |
// XXX The display could be obtained from any object created by it, so we can |
| 68 |
// query it from the config. |
| 69 |
let gl_display = gl_config.display(); |
| 70 |
|
| 71 |
// Glutin tries to create an OpenGL context by default. Force it to use any version of GLES. |
| 72 |
let context_attributes = glutin::context::ContextAttributesBuilder::new() |
| 73 |
// WGPU expects GLES 3.0+. |
| 74 |
.with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0)))) |
| 75 |
.build(raw_window_handle); |
| 76 |
|
| 77 |
let mut not_current_gl_context = Some(unsafe { |
| 78 |
gl_display |
| 79 |
.create_context(&gl_config, &context_attributes) |
| 80 |
.expect("failed to create context") |
| 81 |
}); |
| 82 |
|
| 83 |
let mut state = None; |
| 84 |
|
| 85 |
// Only needs to be loaded once |
| 86 |
let mut exposed = None; |
| 87 |
|
| 88 |
event_loop |
| 89 |
.run(move |event, window_target| { |
| 90 |
use winit::{ |
| 91 |
event::{Event, KeyEvent, WindowEvent}, |
| 92 |
event_loop::ControlFlow, |
| 93 |
keyboard::{Key, NamedKey}, |
| 94 |
}; |
| 95 |
window_target.set_control_flow(ControlFlow::Wait); |
| 96 |
|
| 97 |
match event { |
| 98 |
// Event::LoopExiting => (), |
| 99 |
Event::WindowEvent { |
| 100 |
window_id: _, |
| 101 |
event: |
| 102 |
WindowEvent::CloseRequested |
| 103 |
| WindowEvent::KeyboardInput { |
| 104 |
event: |
| 105 |
KeyEvent { |
| 106 |
logical_key: Key::Named(NamedKey::Escape), |
| 107 |
.. |
| 108 |
}, |
| 109 |
.. |
| 110 |
}, |
| 111 |
} => window_target.exit(), |
| 112 |
Event::Resumed => { |
| 113 |
let window = window.take().unwrap_or_else(|| { |
| 114 |
let window_builder = winit::window::WindowBuilder::new() |
| 115 |
.with_title("WGPU raw GLES example (press Escape to exit)"); |
| 116 |
glutin_winit::finalize_window(window_target, window_builder, &gl_config) |
| 117 |
.unwrap() |
| 118 |
}); |
| 119 |
|
| 120 |
let attrs = window.build_surface_attributes(Default::default()); |
| 121 |
let gl_surface = unsafe { |
| 122 |
gl_config |
| 123 |
.display() |
| 124 |
.create_window_surface(&gl_config, &attrs) |
| 125 |
.expect("Cannot create GL WindowSurface") |
| 126 |
}; |
| 127 |
|
| 128 |
// Make it current. |
| 129 |
let gl_context = not_current_gl_context |
| 130 |
.take() |
| 131 |
.unwrap() |
| 132 |
.make_current(&gl_surface) |
| 133 |
.expect("GL context cannot be made current with WindowSurface"); |
| 134 |
|
| 135 |
// The context needs to be current for the Renderer to set up shaders and |
| 136 |
// buffers. It also performs function loading, which needs a current context on |
| 137 |
// WGL. |
| 138 |
println!("Hooking up to wgpu-hal"); |
| 139 |
exposed.get_or_insert_with(|| { |
| 140 |
unsafe { |
| 141 |
<hal::api::Gles as hal::Api>::Adapter::new_external( |
| 142 |
|name| { |
| 143 |
// XXX: On WGL this should only be called after the context was made current |
| 144 |
gl_config |
| 145 |
.display() |
| 146 |
.get_proc_address(&CString::new(name).expect(name)) |
| 147 |
}, |
| 148 |
wgpu_types::GlBackendOptions::default(), |
| 149 |
) |
| 150 |
} |
| 151 |
.expect("GL adapter can't be initialized") |
| 152 |
}); |
| 153 |
|
| 154 |
assert!(state.replace((gl_context, gl_surface, window)).is_none()); |
| 155 |
} |
| 156 |
Event::Suspended => { |
| 157 |
// This event is only raised on Android, where the backing NativeWindow for a GL |
| 158 |
// Surface can appear and disappear at any moment. |
| 159 |
println!("Android window removed"); |
| 160 |
|
| 161 |
// Destroy the GL Surface and un-current the GL Context before ndk-glue releases |
| 162 |
// the window back to the system. |
| 163 |
let (gl_context, ..) = state.take().unwrap(); |
| 164 |
assert!(not_current_gl_context |
| 165 |
.replace(gl_context.make_not_current().unwrap()) |
| 166 |
.is_none()); |
| 167 |
} |
| 168 |
Event::WindowEvent { |
| 169 |
window_id: _, |
| 170 |
event: WindowEvent::Resized(size), |
| 171 |
} => { |
| 172 |
if size.width != 0 && size.height != 0 { |
| 173 |
// Some platforms like EGL require resizing GL surface to update the size |
| 174 |
// Notable platforms here are Wayland and macOS, other don't require it |
| 175 |
// and the function is no-op, but it's wise to resize it for portability |
| 176 |
// reasons. |
| 177 |
if let Some((gl_context, gl_surface, _)) = &state { |
| 178 |
gl_surface.resize( |
| 179 |
gl_context, |
| 180 |
NonZeroU32::new(size.width).unwrap(), |
| 181 |
NonZeroU32::new(size.height).unwrap(), |
| 182 |
); |
| 183 |
// XXX: If there's a state for fill_screen(), this would need to be updated too. |
| 184 |
} |
| 185 |
} |
| 186 |
} |
| 187 |
Event::WindowEvent { |
| 188 |
window_id: _, |
| 189 |
event: WindowEvent::RedrawRequested, |
| 190 |
} => { |
| 191 |
if let (Some(exposed), Some((gl_context, gl_surface, window))) = |
| 192 |
(&exposed, &state) |
| 193 |
{ |
| 194 |
let inner_size = window.inner_size(); |
| 195 |
|
| 196 |
fill_screen(exposed, inner_size.width, inner_size.height); |
| 197 |
|
| 198 |
println!("Showing the window"); |
| 199 |
gl_surface |
| 200 |
.swap_buffers(gl_context) |
| 201 |
.expect("Failed to swap buffers"); |
| 202 |
} |
| 203 |
} |
| 204 |
_ => (), |
| 205 |
} |
| 206 |
}) |
| 207 |
.expect("Couldn't run event loop"); |
| 208 |
} |
| 209 |
|
| 210 |
#[cfg(target_os = "emscripten")] |
| 211 |
fn main() { |
| 212 |
env_logger::init(); |
| 213 |
|
| 214 |
println!("Initializing external GL context"); |
| 215 |
let egl = khronos_egl::Instance::new(khronos_egl::Static); |
| 216 |
let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.unwrap(); |
| 217 |
egl.initialize(display) |
| 218 |
.expect("unable to initialize display"); |
| 219 |
|
| 220 |
let attributes = [ |
| 221 |
khronos_egl::RED_SIZE, |
| 222 |
8, |
| 223 |
khronos_egl::GREEN_SIZE, |
| 224 |
8, |
| 225 |
khronos_egl::BLUE_SIZE, |
| 226 |
8, |
| 227 |
khronos_egl::NONE, |
| 228 |
]; |
| 229 |
|
| 230 |
let config = egl |
| 231 |
.choose_first_config(display, &attributes) |
| 232 |
.unwrap() |
| 233 |
.expect("unable to choose config"); |
| 234 |
let surface = unsafe { |
| 235 |
let window = std::ptr::null_mut::<std::ffi::c_void>(); |
| 236 |
egl.create_window_surface(display, config, window, None) |
| 237 |
} |
| 238 |
.expect("unable to create surface"); |
| 239 |
|
| 240 |
let context_attributes = [khronos_egl::CONTEXT_CLIENT_VERSION, 3, khronos_egl::NONE]; |
| 241 |
|
| 242 |
let gl_context = egl |
| 243 |
.create_context(display, config, None, &context_attributes) |
| 244 |
.expect("unable to create context"); |
| 245 |
egl.make_current(display, Some(surface), Some(surface), Some(gl_context)) |
| 246 |
.expect("can't make context current"); |
| 247 |
|
| 248 |
println!("Hooking up to wgpu-hal"); |
| 249 |
let exposed = unsafe { |
| 250 |
<hal::api::Gles as hal::Api>::Adapter::new_external(|name| { |
| 251 |
egl.get_proc_address(name) |
| 252 |
.map_or(std::ptr::null(), |p| p as *const _) |
| 253 |
}) |
| 254 |
} |
| 255 |
.expect("GL adapter can't be initialized"); |
| 256 |
|
| 257 |
fill_screen(&exposed, 640, 400); |
| 258 |
} |
| 259 |
|
| 260 |
#[cfg(any( |
| 261 |
all(target_arch = "wasm32", not(target_os = "emscripten")), |
| 262 |
target_os = "ios", |
| 263 |
target_os = "visionos" |
| 264 |
))] |
| 265 |
fn main() { |
| 266 |
eprintln!("This example is not supported on Windows and non-emscripten wasm32") |
| 267 |
} |
| 268 |
|
| 269 |
#[cfg(not(any( |
| 270 |
all(target_arch = "wasm32", not(target_os = "emscripten")), |
| 271 |
target_os = "ios", |
| 272 |
target_os = "visionos" |
| 273 |
)))] |
| 274 |
fn fill_screen(exposed: &hal::ExposedAdapter<hal::api::Gles>, width: u32, height: u32) { |
| 275 |
use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _}; |
| 276 |
|
| 277 |
let od = unsafe { |
| 278 |
exposed.adapter.open( |
| 279 |
wgpu_types::Features::empty(), |
| 280 |
&wgpu_types::Limits::downlevel_defaults(), |
| 281 |
&wgpu_types::MemoryHints::default(), |
| 282 |
) |
| 283 |
} |
| 284 |
.unwrap(); |
| 285 |
|
| 286 |
let format = wgpu_types::TextureFormat::Rgba8UnormSrgb; |
| 287 |
let texture = <hal::api::Gles as hal::Api>::Texture::default_framebuffer(format); |
| 288 |
let view = unsafe { |
| 289 |
od.device |
| 290 |
.create_texture_view( |
| 291 |
&texture, |
| 292 |
&hal::TextureViewDescriptor { |
| 293 |
label: None, |
| 294 |
format, |
| 295 |
dimension: wgpu_types::TextureViewDimension::D2, |
| 296 |
usage: wgpu_types::TextureUses::COLOR_TARGET, |
| 297 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 298 |
}, |
| 299 |
) |
| 300 |
.unwrap() |
| 301 |
}; |
| 302 |
|
| 303 |
println!("Filling the screen"); |
| 304 |
let mut encoder = unsafe { |
| 305 |
od.device |
| 306 |
.create_command_encoder(&hal::CommandEncoderDescriptor { |
| 307 |
label: None, |
| 308 |
queue: &od.queue, |
| 309 |
}) |
| 310 |
.unwrap() |
| 311 |
}; |
| 312 |
let mut fence = unsafe { od.device.create_fence().unwrap() }; |
| 313 |
let rp_desc = hal::RenderPassDescriptor { |
| 314 |
label: None, |
| 315 |
extent: wgpu_types::Extent3d { |
| 316 |
width, |
| 317 |
height, |
| 318 |
depth_or_array_layers: 1, |
| 319 |
}, |
| 320 |
sample_count: 1, |
| 321 |
color_attachments: &[Some(hal::ColorAttachment { |
| 322 |
target: hal::Attachment { |
| 323 |
view: &view, |
| 324 |
usage: wgpu_types::TextureUses::COLOR_TARGET, |
| 325 |
}, |
| 326 |
depth_slice: None, |
| 327 |
resolve_target: None, |
| 328 |
ops: hal::AttachmentOps::STORE, |
| 329 |
clear_value: wgpu_types::Color::BLUE, |
| 330 |
})], |
| 331 |
depth_stencil_attachment: None, |
| 332 |
multiview: None, |
| 333 |
timestamp_writes: None, |
| 334 |
occlusion_query_set: None, |
| 335 |
}; |
| 336 |
unsafe { |
| 337 |
encoder.begin_encoding(None).unwrap(); |
| 338 |
encoder.begin_render_pass(&rp_desc).unwrap(); |
| 339 |
encoder.end_render_pass(); |
| 340 |
let cmd_buf = encoder.end_encoding().unwrap(); |
| 341 |
od.queue.submit(&[&cmd_buf], &[], (&mut fence, 0)).unwrap(); |
| 342 |
} |
| 343 |
} |