mirror of
https://github.com/penpot/penpot.git
synced 2025-12-12 06:24:17 +01:00
87 lines
2.6 KiB
Rust
87 lines
2.6 KiB
Rust
use skia_safe as skia;
|
|
use skia_safe::gpu::{self, gl::FramebufferInfo, DirectContext};
|
|
|
|
extern "C" {
|
|
pub fn emscripten_GetProcAddress(
|
|
name: *const ::std::os::raw::c_char,
|
|
) -> *const ::std::os::raw::c_void;
|
|
}
|
|
|
|
pub struct GpuState {
|
|
pub context: DirectContext,
|
|
framebuffer_info: FramebufferInfo,
|
|
}
|
|
|
|
/// This struct holds the state of the Rust application between JS calls.
|
|
///
|
|
/// It is created by [init] and passed to the other exported functions. Note that rust-skia data
|
|
/// structures are not thread safe, so a state must not be shared between different Web Workers.
|
|
pub struct State {
|
|
pub gpu_state: GpuState,
|
|
pub surface: skia::Surface,
|
|
}
|
|
|
|
impl State {
|
|
pub fn new(gpu_state: GpuState, surface: skia::Surface) -> Self {
|
|
State { gpu_state, surface }
|
|
}
|
|
|
|
pub fn set_surface(&mut self, surface: skia::Surface) {
|
|
self.surface = surface;
|
|
}
|
|
}
|
|
|
|
pub(crate) fn init_gl() {
|
|
unsafe {
|
|
gl::load_with(|addr| {
|
|
let addr = std::ffi::CString::new(addr).unwrap();
|
|
emscripten_GetProcAddress(addr.into_raw() as *const _) as *const _
|
|
});
|
|
}
|
|
}
|
|
|
|
/// This needs to be done once per WebGL context.
|
|
pub(crate) fn create_gpu_state() -> GpuState {
|
|
let interface = skia_safe::gpu::gl::Interface::new_native().unwrap();
|
|
let context = skia_safe::gpu::direct_contexts::make_gl(interface, None).unwrap();
|
|
let framebuffer_info = {
|
|
let mut fboid: gl::types::GLint = 0;
|
|
unsafe { gl::GetIntegerv(gl::FRAMEBUFFER_BINDING, &mut fboid) };
|
|
|
|
FramebufferInfo {
|
|
fboid: fboid.try_into().unwrap(),
|
|
format: skia_safe::gpu::gl::Format::RGBA8.into(),
|
|
protected: skia_safe::gpu::Protected::No,
|
|
}
|
|
};
|
|
|
|
GpuState {
|
|
context,
|
|
framebuffer_info,
|
|
}
|
|
}
|
|
|
|
/// Create the Skia surface that will be used for rendering.
|
|
pub(crate) fn create_surface(gpu_state: &mut GpuState, width: i32, height: i32) -> skia::Surface {
|
|
let backend_render_target =
|
|
gpu::backend_render_targets::make_gl((width, height), 1, 8, gpu_state.framebuffer_info);
|
|
|
|
gpu::surfaces::wrap_backend_render_target(
|
|
&mut gpu_state.context,
|
|
&backend_render_target,
|
|
skia_safe::gpu::SurfaceOrigin::BottomLeft,
|
|
skia_safe::ColorType::RGBA8888,
|
|
None,
|
|
None,
|
|
)
|
|
.unwrap()
|
|
}
|
|
|
|
pub(crate) fn render_rect(surface: &mut skia::Surface, rect: skia::Rect, color: skia::Color) {
|
|
let mut paint = skia::Paint::default();
|
|
paint.set_style(skia::PaintStyle::Fill);
|
|
paint.set_color(color);
|
|
paint.set_anti_alias(true);
|
|
surface.canvas().draw_rect(rect, &paint);
|
|
}
|