use std::sync::{Arc, Mutex, MutexGuard};
#[derive(Debug, Clone)]
pub struct ShaderMaterial {
pub fragment: String,
pub vertex: Option<String>,
pub data: Vec<[f32; 4]>,
pub storage0: Vec<f32>,
pub storage1: Vec<f32>,
pub storage2: Vec<f32>,
#[cfg(feature = "render")]
pub textures: Vec<crate::marks::gpu::TextureView>,
pub maps: Vec<std::sync::Arc<crate::textures::Texture>>,
#[cfg(feature = "render")]
pub volumes: Vec<crate::marks::gpu::TextureView>,
#[cfg(feature = "render")]
pub volume_maps: Vec<std::sync::Arc<crate::volume::Data3DTexture>>,
pub screen_space: bool,
pub opacity: f32,
pub transparent: bool,
pub side: u32,
pub tone_mapped: bool,
pub render_state: super::RenderState,
pub fallback_color: crate::math::Color,
pub msl: Option<String>,
pub alpha_to_coverage: bool,
pub shadow_vertex: bool,
pub live: ShaderLive,
}
pub struct ShaderLive {
id: u64,
field_rev: [u64; 3],
shared: Arc<LiveShared>,
}
struct LiveShared {
id: u64,
state: Mutex<LiveState>,
}
#[derive(Default)]
pub(crate) struct LiveState {
pub(crate) data: Option<[[f32; 4]; 16]>,
pub(crate) storage: [Option<LiveSlot>; 3],
}
pub(crate) struct LiveSlot {
pub(crate) data: Vec<f32>,
pub(crate) version: u64,
pub(crate) base: u64,
pub(crate) ranges: std::collections::VecDeque<(u64, usize, usize)>,
}
const RANGE_LOG: usize = 256;
fn next_id() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
impl Default for ShaderLive {
fn default() -> Self {
Self {
id: next_id(),
field_rev: [0; 3],
shared: Arc::new(LiveShared {
id: next_id(),
state: Mutex::new(LiveState::default()),
}),
}
}
}
impl Clone for ShaderLive {
fn clone(&self) -> Self {
Self {
id: next_id(),
field_rev: self.field_rev,
shared: self.shared.clone(),
}
}
}
impl std::fmt::Debug for ShaderLive {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ShaderLive")
.field("id", &self.id)
.field("shared", &self.shared.id)
.finish()
}
}
impl ShaderLive {
#[cfg_attr(not(feature = "render"), allow(dead_code))]
pub(crate) fn id(&self) -> u64 {
self.id
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
pub(crate) fn shared_id(&self) -> u64 {
self.shared.id
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
pub(crate) fn field_rev(&self, slot: usize) -> u64 {
self.field_rev[slot]
}
pub(crate) fn lock(&self) -> MutexGuard<'_, LiveState> {
self.shared.state.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl Default for ShaderMaterial {
fn default() -> Self {
Self {
fragment: String::new(),
vertex: None,
data: Vec::new(),
storage0: Vec::new(),
storage1: Vec::new(),
storage2: Vec::new(),
#[cfg(feature = "render")]
textures: Vec::new(),
maps: Vec::new(),
#[cfg(feature = "render")]
volumes: Vec::new(),
#[cfg(feature = "render")]
volume_maps: Vec::new(),
screen_space: false,
opacity: 1.0,
transparent: false,
side: 0,
tone_mapped: true,
render_state: super::RenderState::DEFAULT,
fallback_color: crate::math::Color::WHITE,
msl: None,
alpha_to_coverage: false,
shadow_vertex: false,
live: ShaderLive::default(),
}
}
}
impl ShaderMaterial {
pub fn new(fragment: impl Into<String>) -> Self {
Self {
fragment: fragment.into(),
..Default::default()
}
}
pub fn from_shared(shader: &super::SharedShader) -> Self {
Self::try_from_shared(shader).unwrap_or_else(|e| panic!("{e}"))
}
pub fn try_from_shared(shader: &super::SharedShader) -> Result<Self, String> {
#[cfg(feature = "render")]
let msl = Some(shader.msl()?);
#[cfg(not(feature = "render"))]
let msl = None;
Ok(Self {
fragment: shader.wgsl()?,
msl,
..Default::default()
})
}
pub fn with_msl(mut self, msl: impl Into<String>) -> Self {
self.msl = Some(msl.into());
self
}
pub fn with_vertex(mut self, vertex: impl Into<String>) -> Self {
self.vertex = Some(vertex.into());
self
}
pub fn with_depth_write(mut self, write: bool) -> Self {
self.render_state.depth_write = Some(write);
self
}
pub const VALIDATION_AVAILABLE: bool =
!cfg!(any(target_arch = "wasm32", feature = "precompiled-shaders"));
#[cfg(feature = "render")]
pub fn module_source(&self, storage_buffers: bool) -> String {
crate::renderer::custom_shader_module_source(
&self.fragment,
self.vertex.as_deref(),
storage_buffers,
false,
1,
)
}
#[cfg(feature = "render")]
pub fn validate(&self, storage_buffers: bool) -> Result<(), String> {
for (coverage, samples) in [(false, 1), (self.alpha_to_coverage, 4)] {
let source = crate::renderer::custom_shader_module_source(
&self.fragment,
self.vertex.as_deref(),
storage_buffers,
coverage,
samples,
);
crate::renderer::validate_custom_shader(
&source,
crate::renderer::custom_preamble_lines(),
)?;
}
Ok(())
}
pub fn with_data(mut self, data: Vec<[f32; 4]>) -> Self {
self.data = data;
self
}
pub fn with_storage0(mut self, s: Vec<f32>) -> Self {
self.storage0 = s;
self
}
pub fn with_storage1(mut self, s: Vec<f32>) -> Self {
self.storage1 = s;
self
}
pub fn with_storage2(mut self, s: Vec<f32>) -> Self {
self.storage2 = s;
self
}
#[cfg(feature = "render")]
pub fn with_textures<T: Into<crate::marks::gpu::TextureView>>(
mut self,
t: impl IntoIterator<Item = T>,
) -> Self {
self.textures = t.into_iter().map(Into::into).collect();
self
}
pub fn with_maps(mut self, maps: Vec<std::sync::Arc<crate::textures::Texture>>) -> Self {
self.maps = maps;
self
}
#[cfg(feature = "render")]
pub fn with_volume_maps(
mut self,
volumes: Vec<std::sync::Arc<crate::volume::Data3DTexture>>,
) -> Self {
self.volume_maps = volumes;
self
}
pub fn with_screen_space(mut self, on: bool) -> Self {
self.screen_space = on;
self
}
pub fn with_opacity(mut self, opacity: f32) -> Self {
self.opacity = opacity;
self
}
pub fn with_transparent(mut self, transparent: bool) -> Self {
self.transparent = transparent;
self
}
pub fn with_side(mut self, side: u32) -> Self {
self.side = side;
self
}
pub fn data_slots(&self) -> [[f32; 4]; 16] {
if let Some(d) = self.live.lock().data {
return d;
}
self.field_slots()
}
pub(crate) fn field_slots(&self) -> [[f32; 4]; 16] {
let mut out = [[0.0f32; 4]; 16];
for (i, v) in self.data.iter().take(16).enumerate() {
out[i] = *v;
}
out
}
pub fn set_data(&self, data: &[[f32; 4]]) {
let mut out = [[0.0f32; 4]; 16];
for (i, v) in data.iter().take(16).enumerate() {
out[i] = *v;
}
self.live.lock().data = Some(out);
}
pub fn set_uniform(&self, slot: usize, value: [f32; 4]) {
if slot >= 16 {
return;
}
let base = self.field_slots();
let mut st = self.live.lock();
st.data.get_or_insert(base)[slot] = value;
}
pub fn set_data_floats(&self, offset: usize, values: &[f32]) {
let base = self.field_slots();
let mut st = self.live.lock();
let d = st.data.get_or_insert(base);
for (k, v) in values.iter().enumerate() {
let i = offset + k;
if i >= 64 {
break;
}
d[i / 4][i % 4] = *v;
}
}
pub fn set_storage(&self, slot: usize, data: Vec<f32>) {
let Some(slot) = Self::slot(slot) else { return };
let mut st = self.live.lock();
let version = st.storage[slot].as_ref().map_or(0, |s| s.version) + 1;
st.storage[slot] = Some(LiveSlot {
data,
version,
base: version,
ranges: Default::default(),
});
}
pub fn set_storage_range(&self, slot: usize, offset: usize, values: &[f32]) {
let Some(slot) = Self::slot(slot) else { return };
if values.is_empty() {
return;
}
let mut st = self.live.lock();
let s = st.storage[slot].get_or_insert_with(|| LiveSlot {
data: self.storage_field(slot).to_vec(),
version: 1,
base: 1,
ranges: Default::default(),
});
let end = offset + values.len();
s.version += 1;
if end > s.data.len() {
s.data.resize(end, 0.0);
s.base = s.version;
s.ranges.clear();
} else {
if s.ranges.len() == RANGE_LOG {
s.ranges.pop_front();
}
s.ranges.push_back((s.version, offset, end));
}
s.data[offset..end].copy_from_slice(values);
}
pub fn mark_storage_dirty(&mut self, slot: usize) {
if let Some(slot) = Self::slot(slot) {
self.live.field_rev[slot] += 1;
}
}
fn slot(slot: usize) -> Option<usize> {
(slot < 3).then_some(slot)
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
pub(crate) fn storage_stamps(&self) -> [u64; 3] {
let live = self.live.lock();
std::array::from_fn(|slot| match &live.storage[slot] {
Some(ls) => ls.version ^ (self.live.shared_id() << 20) ^ (1 << 63),
None => {
let f = self.storage_field(slot);
(f.as_ptr() as u64)
^ (f.len() as u64).rotate_left(40)
^ self.live.field_rev(slot).rotate_left(20)
}
})
}
pub fn storage(&self, slot: usize) -> std::borrow::Cow<'_, [f32]> {
let live = self.live.lock();
match live.storage.get(slot).and_then(|s| s.as_ref()) {
Some(ls) => std::borrow::Cow::Owned(ls.data.clone()),
None => std::borrow::Cow::Borrowed(self.storage_field(slot)),
}
}
pub(crate) fn storage_field(&self, slot: usize) -> &[f32] {
match slot {
0 => &self.storage0,
1 => &self.storage1,
_ => &self.storage2,
}
}
}