use ::wgpu;
use std::any::TypeId;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use crate::canvas_scene::{CustomShaderId, Viewport2D};
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
pub struct CustomShaderViewport {
pub target_size: [f32; 2],
pub canvas_origin: [f32; 2],
pub canvas_size: [f32; 2],
pub camera: [f32; 4],
pub is_srgb: f32,
pub _pad: f32,
}
impl CustomShaderViewport {
#[inline]
pub fn from_viewport2d(
target_w: u32,
target_h: u32,
canvas_x: f32,
canvas_y: f32,
canvas_w: f32,
canvas_h: f32,
vp: Viewport2D,
scale_factor: f32,
is_srgb: bool,
) -> Self {
Self {
target_size: [target_w as f32, target_h as f32],
canvas_origin: [canvas_x, canvas_y],
canvas_size: [canvas_w, canvas_h],
camera: [
canvas_x + vp.offset_x * scale_factor,
canvas_y + vp.offset_y * scale_factor,
vp.zoom * scale_factor,
scale_factor,
],
is_srgb: if is_srgb { 1.0 } else { 0.0 },
_pad: 0.0,
}
}
}
pub trait CustomShaderPrimitive: Send + Sync + 'static {
fn prepare(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
target_format: wgpu::TextureFormat,
viewport: &CustomShaderViewport,
uniform_bytes: &[u8],
);
fn render<'pass>(&'pass self, render_pass: &mut wgpu::RenderPass<'pass>);
}
struct RegisteredEntry {
_type_id: TypeId,
shader: Arc<dyn CustomShaderPrimitive>,
}
static NEXT_CUSTOM_SHADER_ID: AtomicU32 = AtomicU32::new(1);
fn global_registry() -> &'static Mutex<HashMap<CustomShaderId, RegisteredEntry>> {
static REG: OnceLock<Mutex<HashMap<CustomShaderId, RegisteredEntry>>> = OnceLock::new();
REG.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn register_custom_shader<S: CustomShaderPrimitive>(shader: S) -> CustomShaderId {
let id = CustomShaderId(NEXT_CUSTOM_SHADER_ID.fetch_add(1, Ordering::Relaxed));
let entry = RegisteredEntry {
_type_id: TypeId::of::<S>(),
shader: Arc::new(shader),
};
if let Ok(mut map) = global_registry().lock() {
map.insert(id, entry);
}
id
}
pub fn unregister_custom_shader(id: CustomShaderId) -> bool {
global_registry()
.lock()
.ok()
.and_then(|mut map| map.remove(&id))
.is_some()
}
pub(crate) fn lookup_custom_shader(id: CustomShaderId) -> Option<Arc<dyn CustomShaderPrimitive>> {
global_registry()
.lock()
.ok()
.and_then(|map| map.get(&id).map(|e| Arc::clone(&e.shader)))
}