use std::any::Any;
use std::sync::Arc;
use mln_gfx::gfx_types::AttributeDataType;
use mln_gfx::shaders::bindings::{
FIRST_UNIFORM_ID, FIRST_VERTICES_ID, MAX_ATTRIBUTES, MAX_TEXTURES, UNIFORM_SLOTS, VERTICES_SLOTS,
};
use mln_gfx::shaders::block::{Block, Member, MemberType};
use mln_gfx::shaders::program::{
Attribute, BufferKind, Program, ProgramBuffer, ProgramTexture, Projection, Property, Stages, TextureRead, Variants,
VertexWord,
};
use mln_gfx::shaders::source::{
GlslEsDeclarations, GlslEsSource, GlslSource, MslSource, Precision, Sources, WgslSource,
};
use mln_plugin::backend::ProgramHandle;
use mln_plugin::{
AttributeDesc, AttributeFormat, BlockDesc, BlockMemberType, BufferKind as PluginBufferKind, Error, GlslPrecision,
Program as PluginProgram, ProgramDesc, ProjectionMode, Result, ShaderStages, TextureRead as PluginTextureRead,
Variants as PluginVariants,
};
use mln_style::hash::{HashMap, HashSet};
#[derive(Debug)]
pub(crate) struct EngineProgram {
program: &'static Program,
}
impl EngineProgram {
pub(crate) const fn inner(&self) -> &'static Program {
self.program
}
}
impl ProgramHandle for EngineProgram {
fn buffer_id(&self, name: &str) -> Result<u32> {
for buf in self.program.buffers {
if buf.name == name {
return u32::try_from(buf.id).map_err(|_| Error::invalid_argument("buffer id overflow"));
}
}
Err(Error::not_found(format!("program '{}' has no buffer named '{name}'", self.program.name)))
}
fn texture_slot(&self, name: &str) -> Result<u32> {
for (slot, tex) in self.program.textures.iter().enumerate() {
if tex.name == name {
return u32::try_from(slot).map_err(|_| Error::invalid_argument("texture slot overflow"));
}
}
Err(Error::not_found(format!("program '{}' has no texture named '{name}'", self.program.name)))
}
fn as_any(&self) -> &dyn Any {
self
}
}
pub(crate) fn resolve_attribute_name(program: &'static Program, name: &str) -> Result<&'static str> {
for attr in program.attributes.iter().chain(program.instance_attributes.iter()) {
if attr.name == name {
return Ok(attr.name);
}
}
Err(Error::invalid_argument(format!("program '{}' has no attribute named '{name}'", program.name)))
}
pub(crate) fn resolve_uniform_block(program: &'static Program, buffer_name: &str) -> Result<&'static Block> {
for buffer in program.buffers {
if buffer.name == buffer_name {
return match buffer.kind {
BufferKind::Uniform(block) => Ok(block),
_ => Err(Error::invalid_argument(format!(
"buffer '{buffer_name}' on program '{}' is not a shared layer uniform block",
program.name
))),
};
}
}
Err(Error::invalid_argument(format!("program '{}' has no uniform buffer named '{buffer_name}'", program.name)))
}
pub(crate) fn to_attribute_format(format: AttributeFormat) -> AttributeDataType {
match format {
AttributeFormat::Byte => AttributeDataType::Byte,
AttributeFormat::Byte2 => AttributeDataType::Byte2,
AttributeFormat::Byte3 => AttributeDataType::Byte3,
AttributeFormat::Byte4 => AttributeDataType::Byte4,
AttributeFormat::UByte => AttributeDataType::UByte,
AttributeFormat::UByte2 => AttributeDataType::UByte2,
AttributeFormat::UByte3 => AttributeDataType::UByte3,
AttributeFormat::UByte4 => AttributeDataType::UByte4,
AttributeFormat::Short => AttributeDataType::Short,
AttributeFormat::Short2 => AttributeDataType::Short2,
AttributeFormat::Short3 => AttributeDataType::Short3,
AttributeFormat::Short4 => AttributeDataType::Short4,
AttributeFormat::UShort => AttributeDataType::UShort,
AttributeFormat::UShort2 => AttributeDataType::UShort2,
AttributeFormat::UShort3 => AttributeDataType::UShort3,
AttributeFormat::UShort4 => AttributeDataType::UShort4,
AttributeFormat::Int => AttributeDataType::Int,
AttributeFormat::Int2 => AttributeDataType::Int2,
AttributeFormat::Int3 => AttributeDataType::Int3,
AttributeFormat::Int4 => AttributeDataType::Int4,
AttributeFormat::UInt => AttributeDataType::UInt,
AttributeFormat::UInt2 => AttributeDataType::UInt2,
AttributeFormat::UInt3 => AttributeDataType::UInt3,
AttributeFormat::UInt4 => AttributeDataType::UInt4,
AttributeFormat::Float => AttributeDataType::Float,
AttributeFormat::Float2 => AttributeDataType::Float2,
AttributeFormat::Float3 => AttributeDataType::Float3,
AttributeFormat::Float4 => AttributeDataType::Float4,
AttributeFormat::UByte4Normalized => AttributeDataType::UByte4Normalized,
}
}
fn to_stages(stages: ShaderStages) -> Stages {
match stages {
ShaderStages::Vertex => Stages::Vertex,
ShaderStages::Fragment => Stages::Fragment,
ShaderStages::Both => Stages::Both,
}
}
fn to_projection(mode: ProjectionMode) -> Projection {
match mode {
ProjectionMode::None => Projection::None,
ProjectionMode::PerDraw => Projection::PerDraw,
ProjectionMode::Own => Projection::Own,
}
}
fn to_texture_read(read: PluginTextureRead) -> TextureRead {
match read {
PluginTextureRead::Filtered => TextureRead::Filtered,
PluginTextureRead::Unfiltered => TextureRead::Unfiltered,
PluginTextureRead::Texels => TextureRead::Texels,
}
}
fn to_precision(p: GlslPrecision) -> Precision {
match p {
GlslPrecision::Low => Precision::Low,
GlslPrecision::Medium => Precision::Medium,
GlslPrecision::High => Precision::High,
}
}
fn member_layout(ty: BlockMemberType) -> Result<(MemberType, usize, usize)> {
match ty {
BlockMemberType::Float => Ok((MemberType::Float, 4, 4)),
BlockMemberType::Int => Ok((MemberType::Int, 4, 4)),
BlockMemberType::Uint => Ok((MemberType::Uint, 4, 4)),
BlockMemberType::Vec2 => Ok((MemberType::Vec2, 8, 8)),
BlockMemberType::Vec3 => Ok((MemberType::Vec3, 16, 12)),
BlockMemberType::Vec4 => Ok((MemberType::Vec4, 16, 16)),
BlockMemberType::Mat4 => Ok((MemberType::Mat4, 16, 64)),
BlockMemberType::Vec4Array(array_length) => {
if array_length == 0 {
return Err(Error::invalid_argument("Vec4Array member must have length > 0"));
}
let len =
usize::try_from(array_length).map_err(|_| Error::invalid_argument("Vec4Array length out of range"))?;
let size =
len.checked_mul(16).ok_or_else(|| Error::invalid_argument("Vec4Array member byte size overflow"))?;
Ok((MemberType::Vec4Array(len), 16, size))
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ValidatedMember {
name: String,
ty: MemberType,
offset: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct ValidatedBlock {
name: String,
size: usize,
members: Vec<ValidatedMember>,
}
enum ValidatedVariants {
All,
Standing,
PerVertex,
Defined(String),
}
enum ValidatedBufferKind {
Uniform(ValidatedBlock),
DrawUniform(ValidatedBlock),
Storage { block: ValidatedBlock, stride: usize },
Vertices(VertexWord),
}
struct ValidatedBuffer {
id: usize,
name: String,
kind: ValidatedBufferKind,
stages: Stages,
variants: ValidatedVariants,
}
struct ValidatedAttribute {
name: String,
format: AttributeDataType,
variants: ValidatedVariants,
}
struct ValidatedTexture {
name: String,
read: TextureRead,
stages: Stages,
variants: ValidatedVariants,
}
fn validate_variants(v: PluginVariants<'_>, label: &str) -> Result<ValidatedVariants> {
match v {
PluginVariants::All => Ok(ValidatedVariants::All),
PluginVariants::Standing => Ok(ValidatedVariants::Standing),
PluginVariants::PerVertex => Ok(ValidatedVariants::PerVertex),
PluginVariants::Defined(text) => {
if text.is_empty() {
return Err(Error::invalid_argument(format!("{label} must not be empty for Variants::Defined")));
}
Ok(ValidatedVariants::Defined(text.to_owned()))
}
}
}
fn validate_block(desc: BlockDesc<'_>, context: &str) -> Result<ValidatedBlock> {
if desc.name.is_empty() {
return Err(Error::invalid_argument(format!("{context}: block name must not be empty")));
}
let byte_size = desc.byte_size as usize;
if byte_size == 0 || !byte_size.is_multiple_of(16) {
return Err(Error::invalid_argument(format!(
"block '{}' byte_size ({byte_size}) must be non-zero and a multiple of 16",
desc.name
)));
}
let mut members = Vec::with_capacity(desc.members.len());
let mut seen_members: HashSet<String> = HashSet::default();
let mut running_offset = 0usize;
for m in desc.members {
if m.name.is_empty() {
return Err(Error::invalid_argument(format!("block '{}' has a member with an empty name", desc.name)));
}
if !seen_members.insert(m.name.to_owned()) {
return Err(Error::invalid_argument(format!("block '{}' has duplicate member '{}'", desc.name, m.name)));
}
let (ty, align, elem_size) = member_layout(m.ty)?;
let offset = m.offset as usize;
if offset != running_offset {
return Err(Error::invalid_argument(format!(
"block '{}' member '{}' offset {offset} does not match expected contiguous offset {running_offset}",
desc.name, m.name
)));
}
if !offset.is_multiple_of(align) {
return Err(Error::invalid_argument(format!(
"block '{}' member '{}' offset {offset} is not aligned to {align} bytes",
desc.name, m.name
)));
}
running_offset = running_offset
.checked_add(elem_size)
.ok_or_else(|| Error::invalid_argument(format!("block '{}' member offset overflow", desc.name)))?;
members.push(ValidatedMember { name: m.name.to_owned(), ty, offset });
}
if running_offset != byte_size {
return Err(Error::invalid_argument(format!(
"block '{}' members end at {running_offset} bytes, expected byte_size {byte_size}",
desc.name
)));
}
Ok(ValidatedBlock { name: desc.name.to_owned(), size: byte_size, members })
}
fn validate_attributes(
attrs: &[AttributeDesc<'_>],
program_name: &str,
seen: &mut HashSet<String>,
) -> Result<Vec<ValidatedAttribute>> {
let mut out = Vec::with_capacity(attrs.len());
for a in attrs {
if a.name.is_empty() {
return Err(Error::invalid_argument(format!(
"program '{program_name}' has an attribute with an empty name"
)));
}
if !seen.insert(a.name.to_owned()) {
return Err(Error::invalid_argument(format!(
"program '{program_name}' has duplicate attribute '{}'",
a.name
)));
}
out.push(ValidatedAttribute {
name: a.name.to_owned(),
format: to_attribute_format(a.format),
variants: validate_variants(a.variants, "attribute.variants")?,
});
}
Ok(out)
}
fn leak_str(s: String) -> &'static str {
Box::leak(s.into_boxed_str())
}
fn leak_slice<T>(v: Vec<T>) -> &'static [T] {
Box::leak(v.into_boxed_slice())
}
fn leak_variants(v: ValidatedVariants) -> Variants {
match v {
ValidatedVariants::All => Variants::All,
ValidatedVariants::Standing => Variants::Standing,
ValidatedVariants::PerVertex => Variants::PerVertex,
ValidatedVariants::Defined(s) => Variants::Defined(leak_str(s)),
}
}
fn leak_block(b: ValidatedBlock) -> &'static Block {
let members: Vec<Member> =
b.members.into_iter().map(|m| Member { name: leak_str(m.name), ty: m.ty, offset: m.offset }).collect();
Box::leak(Box::new(Block { name: leak_str(b.name), size: b.size, members: leak_slice(members) }))
}
pub(crate) fn create_program(desc: &ProgramDesc<'_>) -> Result<PluginProgram> {
if desc.name.is_empty() {
return Err(Error::invalid_argument("program.name must not be empty"));
}
let paint_params = desc.paint_params.map(to_stages);
let projection = to_projection(desc.projection);
let mut buffers = Vec::with_capacity(desc.buffers.len());
let mut seen_buffer_ids = HashSet::default();
let mut seen_buffer_names = HashSet::default();
let mut blocks_by_name: HashMap<String, ValidatedBlock> = HashMap::default();
for (idx, b) in desc.buffers.iter().enumerate() {
if b.name.is_empty() {
return Err(Error::invalid_argument(format!(
"program '{}' buffer[{idx}] name must not be empty",
desc.name
)));
}
if !seen_buffer_names.insert(b.name.to_owned()) {
return Err(Error::invalid_argument(format!(
"program '{}' has duplicate buffer name '{}'",
desc.name, b.name
)));
}
let stages = to_stages(b.stages);
let variants = validate_variants(b.variants, "buffer.variants")?;
let (id, kind) = match b.kind {
PluginBufferKind::Uniform => {
let slot = b.slot as usize;
if slot >= UNIFORM_SLOTS {
return Err(Error::invalid_argument(format!(
"uniform buffer '{}' slot {slot} exceeds maximum ({UNIFORM_SLOTS})",
b.name
)));
}
let block = validate_block(
b.block.ok_or_else(|| {
Error::invalid_argument(format!("uniform buffer '{}' requires a block", b.name))
})?,
b.name,
)?;
(FIRST_UNIFORM_ID + slot, ValidatedBufferKind::Uniform(block))
}
PluginBufferKind::DrawUniform => {
let block = validate_block(
b.block.ok_or_else(|| {
Error::invalid_argument(format!("draw uniform buffer '{}' requires a block", b.name))
})?,
b.name,
)?;
(stages.id(), ValidatedBufferKind::DrawUniform(block))
}
PluginBufferKind::Storage => {
let block = validate_block(
b.block.ok_or_else(|| {
Error::invalid_argument(format!("storage buffer '{}' requires a block", b.name))
})?,
b.name,
)?;
let stride = if b.storage_stride == 0 { block.size } else { b.storage_stride as usize };
if stride < block.size || !stride.is_multiple_of(16) {
return Err(Error::invalid_argument(format!(
"storage buffer '{}' stride ({stride}) must be >= block byte_size ({}) and a multiple of 16",
b.name, block.size
)));
}
(stages.id(), ValidatedBufferKind::Storage { block, stride })
}
PluginBufferKind::VerticesUint | PluginBufferKind::VerticesFloat => {
let slot = b.slot as usize;
if slot >= VERTICES_SLOTS {
return Err(Error::invalid_argument(format!(
"vertex storage buffer '{}' slot {slot} exceeds maximum ({VERTICES_SLOTS})",
b.name
)));
}
if stages != Stages::Vertex {
return Err(Error::invalid_argument(format!(
"vertex storage buffer '{}' must use ShaderStages::Vertex",
b.name
)));
}
if b.block.is_some() {
return Err(Error::invalid_argument(format!(
"vertex storage buffer '{}' must not specify a block",
b.name
)));
}
let word = if b.kind == PluginBufferKind::VerticesUint { VertexWord::Uint } else { VertexWord::Float };
(FIRST_VERTICES_ID + slot, ValidatedBufferKind::Vertices(word))
}
};
if !seen_buffer_ids.insert(id) {
return Err(Error::invalid_argument(format!(
"program '{}' buffer '{}' collides on binding id {id}",
desc.name, b.name
)));
}
if let ValidatedBufferKind::Uniform(ref block)
| ValidatedBufferKind::DrawUniform(ref block)
| ValidatedBufferKind::Storage { ref block, .. } = kind
{
if let Some(existing) = blocks_by_name.get(&block.name) {
if existing != block {
return Err(Error::invalid_argument(format!(
"program '{}' declares block '{}' with conflicting layouts",
desc.name, block.name
)));
}
} else {
blocks_by_name.insert(block.name.clone(), block.clone());
}
}
buffers.push(ValidatedBuffer { id, name: b.name.to_owned(), kind, stages, variants });
}
if desc.attributes.len().saturating_add(desc.instance_attributes.len()) > MAX_ATTRIBUTES {
return Err(Error::invalid_argument(format!(
"program '{}' declares {} attributes, exceeding maximum ({MAX_ATTRIBUTES})",
desc.name,
desc.attributes.len().saturating_add(desc.instance_attributes.len())
)));
}
let mut seen_attrs = HashSet::default();
let attributes = validate_attributes(desc.attributes, desc.name, &mut seen_attrs)?;
let instance_attributes = validate_attributes(desc.instance_attributes, desc.name, &mut seen_attrs)?;
if desc.textures.len() > MAX_TEXTURES {
return Err(Error::invalid_argument(format!(
"program '{}' declares {} textures, exceeding maximum ({MAX_TEXTURES})",
desc.name,
desc.textures.len()
)));
}
let mut textures = Vec::with_capacity(desc.textures.len());
let mut seen_textures = HashSet::default();
for t in desc.textures {
if !t.name.is_empty() && !seen_textures.insert(t.name.to_owned()) {
return Err(Error::invalid_argument(format!(
"program '{}' has duplicate texture name '{}'",
desc.name, t.name
)));
}
textures.push(ValidatedTexture {
name: t.name.to_owned(),
read: to_texture_read(t.read),
stages: to_stages(t.stages),
variants: validate_variants(t.variants, "texture.variants")?,
});
}
let mut properties = Vec::with_capacity(desc.properties.len());
let mut seen_props = HashSet::default();
for &p in desc.properties {
if p.is_empty() {
return Err(Error::invalid_argument(format!("program '{}' has an empty property name", desc.name)));
}
if !seen_props.insert(p.to_owned()) {
return Err(Error::invalid_argument(format!("program '{}' has duplicate property '{p}'", desc.name)));
}
properties.push(p.to_owned());
}
if desc.wgsl.is_none() && desc.msl.is_none() && desc.glsl.is_none() && desc.glsl_es.is_none() {
return Err(Error::invalid_argument(format!(
"program '{}' must provide at least one shader source",
desc.name
)));
}
let mut block_cache: HashMap<String, &'static Block> = HashMap::default();
let mut leak_cached_block = |block: ValidatedBlock| -> &'static Block {
if let Some(&existing) = block_cache.get(&block.name) {
return existing;
}
let key = block.name.clone();
let leaked = leak_block(block);
block_cache.insert(key, leaked);
leaked
};
let leaked_buffers: Vec<ProgramBuffer> = buffers
.into_iter()
.map(|b| {
let kind = match b.kind {
ValidatedBufferKind::Uniform(block) => BufferKind::Uniform(leak_cached_block(block)),
ValidatedBufferKind::DrawUniform(block) => BufferKind::DrawUniform(leak_cached_block(block)),
ValidatedBufferKind::Storage { block, stride } => {
BufferKind::Storage { block: leak_cached_block(block), stride }
}
ValidatedBufferKind::Vertices(word) => BufferKind::Vertices(word),
};
ProgramBuffer {
id: b.id,
name: leak_str(b.name),
kind,
stages: b.stages,
variants: leak_variants(b.variants),
}
})
.collect();
let leaked_attrs: Vec<Attribute> = attributes
.into_iter()
.map(|a| Attribute { name: leak_str(a.name), format: a.format, variants: leak_variants(a.variants) })
.collect();
let leaked_inst_attrs: Vec<Attribute> = instance_attributes
.into_iter()
.map(|a| Attribute { name: leak_str(a.name), format: a.format, variants: leak_variants(a.variants) })
.collect();
let leaked_textures: Vec<ProgramTexture> = textures
.into_iter()
.map(|t| {
if t.name.is_empty() {
ProgramTexture::UNUSED
} else {
ProgramTexture {
name: leak_str(t.name),
read: t.read,
stages: t.stages,
variants: leak_variants(t.variants),
}
}
})
.collect();
let leaked_props: Vec<Property> = properties.into_iter().map(|p| Property { name: leak_str(p) }).collect();
let mut sources = Sources::NONE;
if let Some(w) = desc.wgsl {
let leaked = Box::leak(Box::new(WgslSource {
vertex: (!w.vertex.is_empty()).then(|| leak_str(w.vertex.to_owned())),
fragment: (!w.fragment.is_empty()).then(|| leak_str(w.fragment.to_owned())),
prelude: (!w.prelude.is_empty()).then(|| leak_str(w.prelude.to_owned())),
}));
sources = sources.wgsl(leaked);
}
if let Some(m) = desc.msl {
let leaked = Box::leak(Box::new(MslSource {
vertex_main_function: leak_str(m.vertex_main_function.to_owned()),
fragment_main_function: leak_str(m.fragment_main_function.to_owned()),
source: leak_str(m.source.to_owned()),
fast_math: m.fast_math,
}));
sources = sources.msl(leaked);
}
if let Some(g) = desc.glsl {
let leaked = Box::leak(Box::new(GlslSource {
vertex: leak_str(g.vertex.to_owned()),
fragment: leak_str(g.fragment.to_owned()),
}));
sources = sources.glsl(leaked);
}
if let Some(es) = desc.glsl_es {
let members: Vec<(&'static Block, Precision, &'static [&'static str])> = es
.member_precisions
.iter()
.filter_map(|mp| {
let block = *block_cache.get(mp.block_name)?;
let names: Vec<&'static str> = mp.member_names.iter().map(|s| leak_str((*s).to_owned())).collect();
Some((block, to_precision(mp.precision), leak_slice(names)))
})
.collect();
let attributes: Vec<(Precision, &'static [&'static str])> = es
.attribute_precisions
.iter()
.map(|ap| {
let names: Vec<&'static str> = ap.attribute_names.iter().map(|s| leak_str((*s).to_owned())).collect();
(to_precision(ap.precision), leak_slice(names))
})
.collect();
let highp_samplers: Vec<&'static str> = es.highp_samplers.iter().map(|s| leak_str((*s).to_owned())).collect();
let declarations: &'static GlslEsDeclarations = Box::leak(Box::new(GlslEsDeclarations {
members: leak_slice(members),
attributes: leak_slice(attributes),
highp_samplers: leak_slice(highp_samplers),
}));
let leaked = Box::leak(Box::new(GlslEsSource {
vertex: leak_str(es.vertex.to_owned()),
fragment: leak_str(es.fragment.to_owned()),
declarations,
}));
sources = sources.glsl_es(leaked);
}
let leaked_program: &'static Program = Box::leak(Box::new(Program {
name: leak_str(desc.name.to_owned()),
buffers: leak_slice(leaked_buffers),
paint_params,
projection,
attributes: leak_slice(leaked_attrs),
instance_attributes: leak_slice(leaked_inst_attrs),
textures: leak_slice(leaked_textures),
properties: leak_slice(leaked_props),
sources,
}));
Ok(PluginProgram::from_handle(Arc::new(EngineProgram { program: leaked_program })))
}