use std::sync::{Arc, OnceLock};
use arrayvec::ArrayVec;
use crate::{
Color, Rect,
runtime_shader_source::{
cached_shader_source, cached_shared_shader_source_hash, runtime_shader_overrides_hash,
},
runtime_shader_uniforms::RuntimeShaderUniforms,
tile_mode::TileMode,
};
pub static RUNTIME_SHADER_PRELUDE_WGSL: &str = framework_wgsl!("runtime_shader_prelude.wgsl");
#[derive(Clone, Debug)]
pub struct RuntimeShader {
source: Arc<str>,
source_hash: u64,
uniforms: RuntimeShaderUniforms,
specialization: Option<Arc<ShaderSpecialization>>,
input_padding: f32,
output_padding: f32,
batched_source: bool,
position_independent: bool,
preserves_transparency: bool,
domains: Option<Box<ShaderDomains>>,
placeholder: Option<ShaderPlaceholder>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ShaderPlaceholder {
pub color: Color,
pub shape: Option<PlaceholderShape>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlaceholderShape {
pub bounds: Rect,
pub corner_radius: f32,
}
#[derive(Clone, Debug, Default)]
struct ShaderSpecialization {
overrides: Vec<(&'static str, f64)>,
overrides_hash: OnceLock<u64>,
substrates: ArrayVec<SubstrateSpec, MAX_SUBSTRATES>,
exact: bool,
large_draws: Option<LargeDrawSpecialization>,
}
impl ShaderSpecialization {
fn overrides_hash(&self) -> u64 {
if self.overrides.is_empty() {
return 0;
}
*self.overrides_hash.get_or_init(|| {
#[cfg(test)]
crate::thread_state::with(|state| {
let count = &state.override_hash_computations;
count.set(count.get() + 1);
});
runtime_shader_overrides_hash(self.overrides.iter().copied())
})
}
}
#[derive(Clone, Debug)]
struct LargeDrawSpecialization {
min_pixels: u64,
specialization: Arc<ShaderSpecialization>,
}
#[derive(Clone, Copy, Debug)]
pub struct DrawSpecialization<'a> {
specialization: &'a ShaderSpecialization,
}
impl<'a> DrawSpecialization<'a> {
pub fn overrides(self) -> &'a [(&'static str, f64)] {
&self.specialization.overrides
}
pub fn overrides_hash(self) -> u64 {
self.specialization.overrides_hash()
}
pub fn exact(self) -> bool {
self.specialization.exact
}
}
pub(crate) struct ShaderSpecializationCache<K, const N: usize> {
entries: ArrayVec<CachedShaderSpecialization<K>, N>,
}
struct CachedShaderSpecialization<K> {
source: Option<Arc<ShaderSpecialization>>,
key: K,
result: Option<Arc<ShaderSpecialization>>,
}
impl<K: PartialEq, const N: usize> ShaderSpecializationCache<K, N> {
pub(crate) const fn new() -> Self {
assert!(N > 0);
Self {
entries: ArrayVec::new_const(),
}
}
pub(crate) fn apply(
&mut self,
shader: &mut RuntimeShader,
key: K,
specialize: impl FnOnce(&mut RuntimeShader, &K),
) {
let hit = self.entries.iter().rposition(|entry| {
entry.key == key
&& match (&entry.source, &shader.specialization) {
(Some(source), Some(current)) => Arc::ptr_eq(source, current),
(None, None) => true,
_ => false,
}
});
if let Some(index) = hit {
let entry = self.entries.remove(index);
shader.specialization.clone_from(&entry.result);
self.entries.push(entry);
return;
}
if shader
.specialization
.as_ref()
.is_some_and(|source| Arc::strong_count(source) == 1)
{
specialize(shader, &key);
return;
}
let source = shader.specialization.clone();
specialize(shader, &key);
if self.entries.is_full() {
self.entries.remove(0);
}
self.entries.push(CachedShaderSpecialization {
source,
key,
result: shader.specialization.clone(),
});
}
}
static DEFAULT_SHADER_SPECIALIZATION: ShaderSpecialization = ShaderSpecialization {
overrides: Vec::new(),
overrides_hash: OnceLock::new(),
substrates: ArrayVec::new_const(),
exact: false,
large_draws: None,
};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct ShaderDomains {
output_support: Option<Rect>,
sample_domain: Option<Rect>,
}
fn finite_rect(rect: Option<Rect>) -> Option<Rect> {
rect.filter(|rect| {
rect.x.is_finite()
&& rect.y.is_finite()
&& rect.width.is_finite()
&& rect.height.is_finite()
})
}
pub const MAX_SUBSTRATES: usize = 3;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SubstrateSpec {
Mean,
Average {
block: u32,
},
Blur {
radius_px: f32,
},
}
impl SubstrateSpec {
fn same_bits(&self, other: &Self) -> bool {
match (self, other) {
(Self::Mean, Self::Mean) => true,
(Self::Average { block: a }, Self::Average { block: b }) => a == b,
(Self::Blur { radius_px: a }, Self::Blur { radius_px: b }) => {
a.to_bits() == b.to_bits()
}
_ => false,
}
}
fn hash_bits<H: std::hash::Hasher>(&self, state: &mut H) {
use std::hash::Hash;
match self {
Self::Mean => 2u8.hash(state),
Self::Average { block } => {
0u8.hash(state);
block.hash(state);
}
Self::Blur { radius_px } => {
1u8.hash(state);
radius_px.to_bits().hash(state);
}
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum RuntimeShaderUniformError {
#[error(
"uniform range starting at {index} with width {width} exceeds user uniform range 0..{max_user_uniforms}; slots {reserved_start}..{max_uniforms} are reserved for renderer data"
)]
OutOfUserRange {
index: usize,
width: usize,
max_user_uniforms: usize,
reserved_start: usize,
max_uniforms: usize,
},
}
impl RuntimeShader {
pub const MAX_UNIFORMS: usize = 256;
pub const RESERVED_UNIFORM_START: usize = 220;
pub const QUAD_PLACEMENT_UNIFORM: usize = 220;
pub const SUBSTRATE_REGION_UNIFORMS: [usize; MAX_SUBSTRATES] = [232, 228, 224];
pub const SOURCE_REGION_UNIFORM: usize = 236;
pub const MASK_RECT_UNIFORM: usize = 240;
pub const MASK_RADII_UNIFORM: usize = 244;
pub const EFFECT_RECT_UNIFORM: usize = 248;
pub const LOGICAL_SIZE_UNIFORM: usize = 252;
pub const ALPHA_UNIFORM: usize = 254;
pub const MAX_USER_UNIFORMS: usize = Self::RESERVED_UNIFORM_START;
#[track_caller]
pub fn new(wgsl_source: &str) -> Self {
let (source, source_hash) =
cached_shader_source(std::panic::Location::caller(), wgsl_source);
Self::with_source(source, source_hash)
}
pub fn from_shared_source(source: Arc<str>) -> Self {
let source_hash = cached_shared_shader_source_hash(&source);
Self::with_source(source, source_hash)
}
fn with_source(source: Arc<str>, source_hash: u64) -> Self {
Self {
source,
source_hash,
uniforms: RuntimeShaderUniforms::new(),
specialization: None,
input_padding: 0.0,
output_padding: 0.0,
batched_source: false,
position_independent: false,
preserves_transparency: false,
domains: None,
placeholder: None,
}
}
fn specialization(&self) -> &ShaderSpecialization {
self.specialization
.as_deref()
.unwrap_or(&DEFAULT_SHADER_SPECIALIZATION)
}
fn specialization_mut(&mut self) -> &mut ShaderSpecialization {
Arc::make_mut(self.specialization.get_or_insert_with(Arc::default))
}
pub fn set_override(&mut self, name: &'static str, value: f64) {
self.clear_large_draws();
let position = self
.overrides()
.binary_search_by(|(existing, _)| existing.cmp(&name));
if position.is_ok_and(|index| self.overrides()[index].1.to_bits() == value.to_bits()) {
return;
}
let specialization = self.specialization_mut();
specialization.overrides_hash.take();
let overrides = &mut specialization.overrides;
match position {
Ok(index) => overrides[index].1 = value,
Err(index) => overrides.insert(index, (name, value)),
}
}
pub fn clear_override(&mut self, name: &str) -> bool {
self.clear_large_draws();
let Ok(index) = self
.overrides()
.binary_search_by(|(existing, _)| (*existing).cmp(name))
else {
return false;
};
let specialization = self.specialization_mut();
specialization.overrides_hash.take();
specialization.overrides.remove(index);
true
}
pub fn overrides(&self) -> &[(&'static str, f64)] {
&self.specialization().overrides
}
pub fn overrides_hash(&self) -> u64 {
self.specialization().overrides_hash()
}
pub fn draw_specialization(&self, pixels: u64) -> DrawSpecialization<'_> {
let own = self.specialization();
let specialization = match &own.large_draws {
Some(large) if pixels >= large.min_pixels => &large.specialization,
_ => own,
};
DrawSpecialization { specialization }
}
pub(crate) fn specialize_with_large_draws(
&mut self,
min_pixels: u64,
large: impl FnOnce(&mut Self),
own: impl FnOnce(&mut Self),
) {
let source = self.specialization.clone();
large(self);
let large = std::mem::replace(&mut self.specialization, source);
own(self);
self.specialization_mut().large_draws =
large.map(|specialization| LargeDrawSpecialization {
min_pixels,
specialization,
});
}
pub(crate) fn clear_large_draws(&mut self) {
if self.specialization().large_draws.is_some() {
self.specialization_mut().large_draws = None;
}
}
pub fn set_input_padding(&mut self, padding: f32) {
self.input_padding = if padding.is_finite() {
padding.max(0.0)
} else {
0.0
};
}
pub fn input_padding(&self) -> f32 {
self.input_padding
}
pub fn set_output_padding(&mut self, padding: f32) {
self.output_padding = if padding.is_finite() {
padding.max(0.0)
} else {
0.0
};
}
pub fn output_padding(&self) -> f32 {
self.output_padding
}
pub fn set_output_support(&mut self, support: Option<Rect>) {
self.set_domains(ShaderDomains {
output_support: finite_rect(support),
sample_domain: self.sample_domain(),
});
}
pub fn output_support(&self) -> Option<Rect> {
self.domains
.as_ref()
.and_then(|domains| domains.output_support)
}
fn set_domains(&mut self, domains: ShaderDomains) {
self.domains = (domains != ShaderDomains::default()).then(|| Box::new(domains));
}
pub fn set_sample_domain(&mut self, domain: Option<Rect>) {
self.set_domains(ShaderDomains {
output_support: self.output_support(),
sample_domain: finite_rect(domain),
});
}
pub fn sample_domain(&self) -> Option<Rect> {
self.domains
.as_ref()
.and_then(|domains| domains.sample_domain)
}
pub fn set_float(&mut self, index: usize, value: f32) {
let _ = self.try_set_float(index, value);
}
pub fn try_set_float(
&mut self,
index: usize,
value: f32,
) -> Result<(), RuntimeShaderUniformError> {
self.uniforms.try_write(index, [value])
}
pub fn set_float2(&mut self, index: usize, x: f32, y: f32) {
let _ = self.try_set_float2(index, x, y);
}
pub fn try_set_float2(
&mut self,
index: usize,
x: f32,
y: f32,
) -> Result<(), RuntimeShaderUniformError> {
self.uniforms.try_write(index, [x, y])
}
pub fn set_float4(&mut self, index: usize, x: f32, y: f32, z: f32, w: f32) {
let _ = self.try_set_float4(index, x, y, z, w);
}
pub fn try_set_float4(
&mut self,
index: usize,
x: f32,
y: f32,
z: f32,
w: f32,
) -> Result<(), RuntimeShaderUniformError> {
self.uniforms.try_write(index, [x, y, z, w])
}
pub fn set_batched_source(&mut self, batched: bool) {
self.batched_source = batched;
}
pub fn batched_source(&self) -> bool {
self.batched_source
}
pub fn set_position_independent(&mut self, independent: bool) {
self.position_independent = independent;
}
pub fn position_independent(&self) -> bool {
self.position_independent
}
pub fn set_preserves_transparency(&mut self, preserves: bool) {
self.preserves_transparency = preserves;
}
pub fn preserves_transparency(&self) -> bool {
self.preserves_transparency
}
pub fn set_placeholder(&mut self, placeholder: Option<ShaderPlaceholder>) {
self.placeholder = placeholder;
}
pub fn placeholder(&self) -> Option<ShaderPlaceholder> {
self.placeholder
}
pub fn set_substrates(&mut self, substrates: &[SubstrateSpec]) {
assert!(
substrates.len() <= MAX_SUBSTRATES,
"a runtime shader declares at most {MAX_SUBSTRATES} substrates"
);
self.clear_large_draws();
if self.substrates().len() == substrates.len()
&& self
.substrates()
.iter()
.zip(substrates)
.all(|(existing, incoming)| existing.same_bits(incoming))
{
return;
}
self.specialization_mut().substrates = substrates.iter().copied().collect();
}
pub fn substrates(&self) -> &[SubstrateSpec] {
&self.specialization().substrates
}
pub fn hash_substrates<H: std::hash::Hasher>(&self, state: &mut H) {
use std::hash::Hash;
self.substrates().len().hash(state);
for substrate in self.substrates() {
substrate.hash_bits(state);
}
}
pub fn set_specialization_exact(&mut self, exact: bool) {
self.clear_large_draws();
if self.specialization_exact() == exact {
return;
}
self.specialization_mut().exact = exact;
}
pub fn specialization_exact(&self) -> bool {
self.specialization().exact
}
pub fn source(&self) -> &str {
&self.source
}
pub fn uniforms(&self) -> &[f32] {
self.uniforms.as_slice()
}
pub fn uniforms_padded(&self) -> [f32; Self::MAX_UNIFORMS] {
let mut padded = [0.0f32; Self::MAX_UNIFORMS];
let stored = self.uniforms.as_slice();
padded[..stored.len()].copy_from_slice(stored);
padded
}
pub fn source_hash(&self) -> u64 {
self.source_hash
}
}
impl PartialEq for RuntimeShader {
fn eq(&self, other: &Self) -> bool {
self.source_hash == other.source_hash
&& (Arc::ptr_eq(&self.source, &other.source)
|| self.source.as_ref() == other.source.as_ref())
&& self.uniforms.as_slice() == other.uniforms.as_slice()
&& self.overrides().len() == other.overrides().len()
&& self
.overrides()
.iter()
.zip(other.overrides())
.all(|(a, b)| a.0 == b.0 && a.1.to_bits() == b.1.to_bits())
&& self.input_padding.to_bits() == other.input_padding.to_bits()
&& self.output_padding.to_bits() == other.output_padding.to_bits()
&& self.batched_source == other.batched_source
&& self.position_independent == other.position_independent
&& self.preserves_transparency == other.preserves_transparency
&& self.substrates() == other.substrates()
&& self.domains == other.domains
&& self.placeholder == other.placeholder
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RenderEffect {
Blur {
radius_x: f32,
radius_y: f32,
edge_treatment: TileMode,
},
Offset {
offset_x: f32,
offset_y: f32,
},
Shader {
shader: Arc<RuntimeShader>,
},
Chain {
first: Arc<Self>,
second: Arc<Self>,
},
}
impl RenderEffect {
pub fn placeholder(&self) -> Option<ShaderPlaceholder> {
match self {
Self::Shader { shader } => shader.placeholder(),
Self::Chain { second, .. } => second.placeholder(),
_ => None,
}
}
pub fn blur(radius: f32) -> Self {
Self::blur_with_edge_treatment(radius, TileMode::default())
}
pub fn blur_with_edge_treatment(radius: f32, edge_treatment: TileMode) -> Self {
Self::Blur {
radius_x: radius,
radius_y: radius,
edge_treatment,
}
}
pub fn blur_xy(radius_x: f32, radius_y: f32, edge_treatment: TileMode) -> Self {
Self::Blur {
radius_x,
radius_y,
edge_treatment,
}
}
pub fn offset(offset_x: f32, offset_y: f32) -> Self {
Self::Offset { offset_x, offset_y }
}
pub fn runtime_shader(shader: RuntimeShader) -> Self {
Self::Shader {
shader: Arc::new(shader),
}
}
pub fn then(self, other: Self) -> Self {
Self::Chain {
first: Arc::new(self),
second: Arc::new(other),
}
}
pub fn contains_runtime_shader(&self) -> bool {
match self {
Self::Shader { .. } => true,
Self::Chain { first, second } => {
first.contains_runtime_shader() || second.contains_runtime_shader()
}
_ => false,
}
}
pub fn preserves_transparency(&self) -> bool {
match self {
Self::Blur { .. } | Self::Offset { .. } => true,
Self::Shader { shader } => shader.preserves_transparency(),
Self::Chain { first, second } => {
first.preserves_transparency() && second.preserves_transparency()
}
}
}
pub fn input_padding(&self) -> f32 {
match self {
Self::Blur {
radius_x, radius_y, ..
} => radius_x.abs().max(radius_y.abs()),
Self::Offset { offset_x, offset_y } => offset_x.abs().max(offset_y.abs()),
Self::Shader { shader } => shader.input_padding(),
Self::Chain { first, second } => first.input_padding() + second.input_padding(),
}
}
pub fn output_padding(&self) -> f32 {
match self {
Self::Blur { .. } | Self::Offset { .. } => 0.0,
Self::Shader { shader } => shader.output_padding(),
Self::Chain { first, second } => first.output_padding() + second.output_padding(),
}
}
pub fn output_support(&self) -> Option<Rect> {
match self {
Self::Blur { .. } | Self::Offset { .. } => None,
Self::Shader { shader } => shader.output_support(),
Self::Chain { second, .. } => second.output_support(),
}
}
pub fn sample_domain(&self) -> Option<Rect> {
match self {
Self::Blur { .. } | Self::Offset { .. } => None,
Self::Shader { shader } => shader.sample_domain(),
Self::Chain { second, .. } => second.sample_domain(),
}
}
}
#[cfg(test)]
#[path = "tests/render_effect_tests.rs"]
mod tests;