Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stride of [f32; 4] fields in struct #40

Closed
AndrewBrownK opened this issue Apr 21, 2023 · 1 comment
Closed

Stride of [f32; 4] fields in struct #40

AndrewBrownK opened this issue Apr 21, 2023 · 1 comment

Comments

@AndrewBrownK
Copy link

Pretty new to this so bear with me

wgsl

struct Light {
    position: vec4<f32>,
    color: vec4<f32>,
}

rust

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, encase::ShaderType)]
pub struct Light {
    pub position: [f32; 4],
    pub color: [f32; 4],
}

When I try to use Light in a uniform buffer, I get this failed assertion from Light::assert_uniform_compat():

panicked at 'array stride must be a multiple of 16 (current stride: 4)

[f32; 4] is 16 bytes, yeah? It looks to me that instead of treating each struct field as 16 byte aligned data, it looks into the arrays and treats it like a stride per f32 instead of striding each [f32; 4] whole.

Would it be possible to make Light (as written, with [f32; 4]s) pass assert_uniform_compat?

I looked in the docs and found there is an impl<T> ShaderType for [T]. Maybe this precludes special treatment of [f32; 4]? Is the only solution to pick one of the matrix/vector libraries (like mint or nalgebra) and use that instead of raw [f32; 4]? If so, maybe we can add another example to ShaderType::assert_uniform_compat() to shed light on this scenario?

@teoxoy
Copy link
Owner

teoxoy commented Apr 22, 2023

Since the wgsl spec supports arrays and vectors/matrices have a different layout than bare arrays there had to be a way to distinguish those at the type level.

Arrays used in the uniform address space are required to have a stride that is a multiple of 16, whereas elements of a vec4 do not.

You can either use vector/matrix types from crates supported by encase or create your own newtype around an array and implement the required traits or derive them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants