[glsl-in] Implement std140 and std430 layouts

Structs are not yet implemented
This commit is contained in:
João Capucho authored and Dzmitry Malyshau committed 2021-07-31 23:25:22 -04:00
1 parent e0efe34402
commit e0e840b22c
4 files changed
+180 -10

No files matched your search

+1 -1
View File
@@ -1027,7 +1027,7 @@ pub enum StorageQualifier {
Const,
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructLayout {
Std140,
Std430,
+1
View File
@@ -12,6 +12,7 @@ mod error;
pub use error::ParseError;
mod constants;
mod functions;
mod offset;
mod parser;
#[cfg(test)]
mod parser_tests;
+145
View File
@@ -0,0 +1,145 @@
//! Module responsible for calculating the offset and span for types.
//!
//! There exists two types of layouts std140 and std430 (there's technically
//! two more layouts, shared and packed. Shared is not supported by spirv. Packed is
//! implementation dependent and for now it's just implemented as an alias to
//! std140).
//!
//! The OpenGl spec (the layout rules are defined by the OpenGl spec in section
//! 7.6.2.2 as opposed to the GLSL spec) uses the term basic machine units which are
//! equivalent to bytes.
use super::{ast::StructLayout, error::ErrorKind, SourceMetadata};
use crate::{Arena, Constant, Handle, Type, TypeInner};
/// Struct with information needed for defining a struct member.
///
/// Returned by [`calculate_offset`](calculate_offset)
#[derive(Debug)]
pub struct TypeAlignSpan {
/// The handle to the type, this might be the same handle passed to
/// [`calculate_offset`](calculate_offset) or a new such a new array type
/// with a different stride set.
pub ty: Handle<Type>,
/// The alignment required by the type.
pub align: u32,
/// The size of the type.
pub span: u32,
}
/// Returns the type, alignment and span of a struct member according to a [`StructLayout`](StructLayout).
///
/// The functions returns a [`TypeAlignSpan`](TypeAlignSpan) which has a `ty` member
/// this should be used as the struct member type because for example arrays may have to
/// change the stride and as such need to have a different type.
pub fn calculate_offset(
mut ty: Handle<Type>,
meta: SourceMetadata,
layout: StructLayout,
types: &mut Arena<Type>,
constants: &Arena<Constant>,
) -> Result<TypeAlignSpan, ErrorKind> {
// When using the std430 storage layout, shader storage blocks will be laid out in buffer storage
// identically to uniform and shader storage blocks using the std140 layout, except
// that the base alignment and stride of arrays of scalars and vectors in rule 4 and of
// structures in rule 9 are not rounded up a multiple of the base alignment of a vec4.
let (align, span) = match types[ty].inner {
// 1. If the member is a scalar consuming N basic machine units,
// the base alignment is N.
TypeInner::Scalar { width, .. } => (width as u32, width as u32),
// 2. If the member is a two- or four-component vector with components
// consuming N basic machine units, the base alignment is 2N or 4N, respectively.
// 3. If the member is a three-component vector with components consuming N
// basic machine units, the base alignment is 4N.
TypeInner::Vector { size, width, .. } => {
let val = match size {
crate::VectorSize::Tri => 4 * width as u32,
_ => size as u32 * width as u32,
};
(val, val)
}
// 4. If the member is an array of scalars or vectors, the base alignment and array
// stride are set to match the base alignment of a single array element, according
// to rules (1), (2), and (3), and rounded up to the base alignment of a vec4.
// TODO: Matrices array
TypeInner::Array { base, size, .. } => {
let info = calculate_offset(base, meta, layout, types, constants)?;
let name = types[ty].name.clone();
let mut align = info.align;
let mut stride = (align).max(info.span);
// See comment at the beginning of the function
if StructLayout::Std430 != layout {
stride = align_up(stride, 16);
align = align_up(align, 16);
}
let span = match size {
crate::ArraySize::Constant(s) => {
constants[s].to_array_length().unwrap_or(1) * stride
}
crate::ArraySize::Dynamic => stride,
};
ty = types.fetch_or_append(Type {
name,
inner: TypeInner::Array {
base: info.ty,
size,
stride,
},
});
(align, span)
}
// 5. If the member is a column-major matrix with C columns and R rows, the
// matrix is stored identically to an array of C column vectors with R
// components each, according to rule (4)
// TODO: Row major matrices
TypeInner::Matrix {
columns,
rows,
width,
} => {
let mut align = match rows {
crate::VectorSize::Tri => (4 * width as u32),
_ => (rows as u32 * width as u32),
};
// See comment at the beginning of the function
if StructLayout::Std430 != layout {
align = align_up(align, 16);
}
(align, align * columns as u32)
}
TypeInner::Struct { .. } => todo!(),
_ => {
return Err(ErrorKind::SemanticError(
meta,
"Invalid struct member type".into(),
))
}
};
Ok(TypeAlignSpan { ty, align, span })
}
/// Helper function used for aligning `value` to the next multiple of `align`
///
/// # Notes:
/// - `align` must be a power of two.
/// - The returned value will be greater or equal to `value`.
/// # Examples:
/// ```ignore
/// assert_eq!(0, align_up(0, 16));
/// assert_eq!(16, align_up(1, 16));
/// assert_eq!(16, align_up(16, 16));
/// assert_eq!(334, align_up(333, 2));
/// assert_eq!(384, align_up(257, 128));
/// ```
pub fn align_up(value: u32, align: u32) -> u32 {
((value.wrapping_sub(1)) & !(align - 1)).wrapping_add(align)
}
+33 -9
View File
@@ -5,6 +5,7 @@ use super::{
},
error::ErrorKind,
lex::Lexer,
offset,
token::{SourceMetadata, Token, TokenValue},
variables::{GlobalOrConstant, VarDeclaration},
Program,
@@ -146,7 +147,8 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
let ty_name = self.expect_ident()?.0;
self.expect(TokenValue::LeftBrace)?;
let mut members = Vec::new();
let span = self.parse_struct_declaration_list(&mut members)?;
let span =
self.parse_struct_declaration_list(&mut members, StructLayout::Std140)?;
self.expect(TokenValue::RightBrace)?;
let ty = self.program.module.types.append(Type {
@@ -902,8 +904,16 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
ty_name: String,
mut meta: SourceMetadata,
) -> Result<bool> {
let layout = qualifiers
.iter()
.find_map(|&(ref qualifier, _)| match *qualifier {
TypeQualifier::Layout(layout) => Some(layout),
_ => None,
})
.unwrap_or(StructLayout::Std140);
let mut members = Vec::new();
let span = self.parse_struct_declaration_list(&mut members)?;
let span = self.parse_struct_declaration_list(&mut members, layout)?;
self.expect(TokenValue::RightBrace)?;
let mut ty = self.program.module.types.append(Type {
@@ -977,30 +987,44 @@ impl<'source, 'program, 'options> Parser<'source, 'program, 'options> {
}
// TODO: Accept layout arguments
fn parse_struct_declaration_list(&mut self, members: &mut Vec<StructMember>) -> Result<u32> {
fn parse_struct_declaration_list(
&mut self,
members: &mut Vec<StructMember>,
layout: StructLayout,
) -> Result<u32> {
let mut span = 0;
loop {
// TODO: type_qualifier
let ty = self.parse_type_non_void()?.0;
let name = self.expect_ident()?.0;
let (ty, mut meta) = self.parse_type_non_void()?;
let (name, end_meta) = self.expect_ident()?;
meta = meta.union(&end_meta);
let array_specifier = self.parse_array_specifier()?;
let ty = self.maybe_array(ty, array_specifier);
self.expect(TokenValue::Semicolon)?;
let info = offset::calculate_offset(
ty,
meta,
layout,
&mut self.program.module.types,
&self.program.module.constants,
)?;
span = offset::align_up(span, info.align);
members.push(StructMember {
name: Some(name),
ty,
ty: info.ty,
binding: None,
offset: span,
});
span += self.program.module.types[ty]
.inner
.span(&self.program.module.constants);
span += info.span;
if let TokenValue::RightBrace = self.expect_peek()?.value {
break;