Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ windows-core = { version = "=0.61.2" }
objc2 = "0.6.4"
objc2-core-foundation = { version = "0.3.2", default-features = false, features = ["std", "CFString", "CFUUID", "block2", "objc2"] }
block2 = "0.6.2"
dispatch2 = "0.3.1"
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSEnumerator", "block2", "NSOperation"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
"NSApplication",
Expand All @@ -93,7 +94,7 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = [
] }

[workspace]
members = ["examples/open_parented", "examples/open_window", "examples/render_femtovg"]
members = ["examples/open_parented", "examples/open_window", "examples/render_femtovg", "examples/render_wgpu"]

[lints.clippy]
missing-safety-doc = "allow"
Expand Down
10 changes: 10 additions & 0 deletions examples/render_wgpu/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "render_wgpu"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
baseview = { path = "../..", features = ["opengl"] }
wgpu = "29.0.3"
pollster = "0.4.0"
219 changes: 219 additions & 0 deletions examples/render_wgpu/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
use baseview::dpi::{LogicalSize, PhysicalSize};
use baseview::{
Event, EventStatus, Window, WindowContext, WindowHandler, WindowOpenOptions, WindowSize,
};

use std::cell::RefCell;

struct WgpuExample {
window_context: WindowContext,

instance: wgpu::Instance,
device: wgpu::Device,
pipeline: wgpu::RenderPipeline,
queue: wgpu::Queue,
surface: RefCell<wgpu::Surface<'static>>,
surface_config: RefCell<wgpu::SurfaceConfiguration>,
}

impl WgpuExample {
async fn new(context: WindowContext) -> Self {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle(
Box::new(context.platform_handle()),
));

let surface = instance.create_surface(context.platform_handle()).unwrap();

let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::LowPower,
force_fallback_adapter: false,
// Request an adapter which can render to our surface
compatible_surface: Some(&surface),
})
.await
.expect("Failed to find an appropriate adapter");

// Create the logical device and command queue
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::downlevel_webgl2_defaults()
.using_resolution(adapter.limits()),
memory_hints: wgpu::MemoryHints::MemoryUsage,
..Default::default()
})
.await
.expect("Failed to create device");

const SHADER: &str = "
const VERTS = array(
vec2<f32>(0.5, 1.0),
vec2<f32>(0.0, 0.0),
vec2<f32>(1.0, 0.0)
);

struct VertexOutput {
@builtin(position) clip_position: vec4<f32>,
@location(0) position: vec2<f32>,
};

@vertex
fn vs_main(
@builtin(vertex_index) in_vertex_index: u32,
) -> VertexOutput {
var out: VertexOutput;
out.position = VERTS[in_vertex_index];
out.clip_position = vec4<f32>(out.position - 0.5, 0.0, 1.0);
return out;
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return vec4<f32>(in.position, 0.5, 1.0);
}
";

let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
});

let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
immediate_size: 0,
});

let swapchain_capabilities = surface.get_capabilities(&adapter);
let swapchain_format = swapchain_capabilities.formats[0];

let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(swapchain_format.into())],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});

let PhysicalSize { width, height } = context.size().physical;

let surface_config = surface.get_default_config(&adapter, width, height).unwrap();
surface.configure(&device, &surface_config);

Self {
window_context: context,

instance,
device,
pipeline,
queue,
surface: surface.into(),
surface_config: surface_config.into(),
}
}
}

impl WindowHandler for WgpuExample {
fn on_frame(&self) {
let mut surface = self.surface.borrow_mut();

let surface_texture = match surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(texture) => texture,
wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Timeout => return,
wgpu::CurrentSurfaceTexture::Suboptimal(_) | wgpu::CurrentSurfaceTexture::Outdated => {
surface.configure(&self.device, &self.surface_config.borrow());
// We'll retry next frame
return;
}
wgpu::CurrentSurfaceTexture::Lost => {
*surface =
self.instance.create_surface(self.window_context.platform_handle()).unwrap();
surface.configure(&self.device, &self.surface_config.borrow());

// We'll retry next frame
return;
}
wgpu::CurrentSurfaceTexture::Validation => {
unreachable!("No error scope registered, so validation errors will panic")
}
};

let view = surface_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());

let mut encoder =
self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });

{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});

rpass.set_pipeline(&self.pipeline);
rpass.draw(0..3, 0..1);
}

self.queue.submit(Some(encoder.finish()));
surface_texture.present();
}

fn resized(&self, new_size: WindowSize) {
let mut surface_config = self.surface_config.borrow_mut();

surface_config.width = new_size.physical.width;
surface_config.height = new_size.physical.height;

let surface = self.surface.borrow();
surface.configure(&self.device, &surface_config);
}

fn on_event(&self, event: Event) -> EventStatus {
log_event(&event);

EventStatus::Ignored
}
}

fn main() {
let window_open_options = WindowOpenOptions::new()
.with_title("WGPU on Baseview")
.with_size(LogicalSize::new(512, 512));

Window::open_blocking(window_open_options, |c| pollster::block_on(WgpuExample::new(c)));
}

fn log_event(event: &Event) {
match event {
Event::Mouse(e) => println!("Mouse event: {:?}", e),
Event::Keyboard(e) => println!("Keyboard event: {:?}", e),
Event::Window(e) => println!("Window event: {:?}", e),
}
}
34 changes: 34 additions & 0 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use dpi::{Pixel, Size};
use raw_window_handle::{
DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
};
use std::fmt::Debug;

#[derive(Clone)]
pub struct WindowContext {
Expand Down Expand Up @@ -42,6 +43,10 @@ impl WindowContext {
self.inner.size()
}

pub fn platform_handle(&self) -> PlatformHandle {
PlatformHandle { inner: self.inner.platform_handle() }
}

#[cfg(feature = "opengl")]
pub fn gl_context(&self) -> Option<crate::gl::GlContext> {
self.inner.gl_context()
Expand All @@ -59,3 +64,32 @@ impl HasDisplayHandle for WindowContext {
Ok(self.inner.display_handle())
}
}

#[derive(Clone)]
pub struct PlatformHandle {
inner: platform::PlatformHandle,
}

// Assert that PlatformHandle implements both Send & Sync on all platforms
const _: () = {
const fn assert_impl_all<T: Debug + Send + Sync>() {}
let _: fn() = assert_impl_all::<PlatformHandle>;
};

impl HasWindowHandle for PlatformHandle {
fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
self.inner.window_handle().ok_or(HandleError::Unavailable)
}
}

impl HasDisplayHandle for PlatformHandle {
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
Ok(self.inner.display_handle())
}
}

impl Debug for PlatformHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.fmt(f)
}
}
16 changes: 13 additions & 3 deletions src/platform/macos/context.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
use crate::platform::macos::cursor::Cursor;
use crate::platform::macos::view::BaseviewView;
use crate::platform::WindowSharedState;
use crate::platform::{PlatformHandle, WindowSharedState};
use crate::wrappers::appkit::{View, ViewRef};
use crate::{MouseCursor, WindowSize};
use dispatch2::MainThreadBound;
use dpi::Size;
use objc2::rc::Weak;
use objc2::runtime::NSObjectProtocol;
use objc2::Message;
use objc2::{MainThreadMarker, Message};
use raw_window_handle::DisplayHandle;
use std::rc::Rc;

#[derive(Clone)]
pub struct WindowContext {
mtm: MainThreadMarker,
view: Weak<View<BaseviewView>>,
state: Rc<WindowSharedState>,
}

impl WindowContext {
pub(crate) fn new(view: ViewRef<'_, BaseviewView>) -> Self {
Self { view: Weak::from_retained(&view.view.retain()), state: Rc::clone(&view.state) }
Self {
view: Weak::from_retained(&view.view.retain()),
state: Rc::clone(&view.state),
mtm: view.mtm,
}
}

pub fn close(&self) {
Expand Down Expand Up @@ -86,4 +92,8 @@ impl WindowContext {
pub fn display_handle(&self) -> DisplayHandle<'_> {
DisplayHandle::appkit()
}

pub fn platform_handle(&self) -> PlatformHandle {
PlatformHandle { inner: MainThreadBound::new(self.view.clone(), self.mtm) }
}
}
Loading
Loading