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

Use bytemuck derives instead of unsafe impls #109

Closed
LPGhatguy opened this issue Oct 17, 2020 · 4 comments
Closed

Use bytemuck derives instead of unsafe impls #109

LPGhatguy opened this issue Oct 17, 2020 · 4 comments

Comments

@LPGhatguy
Copy link

In the vertex buffer tutorial, bytemuck is introduced. bytemuck now has a derive feature that enables deriving the traits used in the tutorial. The derive validates that bytemuck's preconditions are met, which can be easy to mess up.

The Vertex would change to this:

#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zezroable)]
struct Vertex {
    position: [f32; 3],
    color: [f32; 3],
}

I tried putting together a PR to make this switch. It was straightforward for this type, but other uses of bytemuck use types from crates like cgmath which do not implement the bytemuck traits. Some people stick with the plain unsafe trait impls for that reason.

I am a little bit paranoid about the ABI of math library types, so I generally use raw types or a crate I built specifically for safe uniform definitions.

@sotrh
Copy link
Owner

sotrh commented Oct 18, 2020

Nice crate 👍 Does the AsStd140 macro align the bytes at the struct level, or is a copy made with the proper alignments when as_bytes is called?

@LPGhatguy
Copy link
Author

The AsStd140 macro generates a new aligned type that your struct is copied into — that type can be safely turned into bytes! I ended up doing that for two reasons after trying to make the user's struct work as-is (based on the shader-types crate):

  • Adding the extra padding fields to the user's struct made the structs a pain to initialize! You can see it in Crevice, but there's a fair bit of ..Zeroable::zeroed() in some of the types.
  • The ABI of some types like matrices doesn't line up with the ABI from math libraries. For example, an std140 mat3 is laid out as vec4[3] instead of vec3[3]. By mapping into a new struct, I could force per-ABI types for these!

For large or dynamically laid out types, I added an interface named Writer, taking ideas from byteorder, a crate I really love.

@sotrh
Copy link
Owner

sotrh commented Oct 19, 2020

Seems like a nice crate. I'll probably use mint for now. I might link to your crate in the tutorial though.

@sotrh
Copy link
Owner

sotrh commented Nov 24, 2020

Fixed in #126

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