Search code examples
rustbevy

Directly adding textures to Assets<Texture> resource causes a gpu_alloc error


I'm loading textures from a file as a Vec<u8> and turning that data into a Texture, when I add that texture to the Asset resource to get a Handle<Texture> it causes two errors, the first one comes from the logging system and says gpu_alloc::block: Memory block wasn't deallocated the second one (which I'm assuming is related) is thread 'main' panicked at 'range end index 32896 out of range for slice of length 32768'. This all seems to stem from this code block

                 Ok(pak) => {
                    let mut assets : CurrentlyLoadedAssets = CurrentlyLoadedAssets::default();
                    for texture in pak.textures {

                        //Creates texture from data and loads it into the resource for a handle
                        let texture_asset: Texture = Texture::new(Extent3d { width: 32, height: 32, depth: 1 }, TextureDimension::D2, texture.1, Rgba8UnormSrgb);

                        //This is causing problems
                        let texture_handle: Handle<Texture> = textures.add(texture_asset);

                        println!("Loading: {}", &texture.0);
                        assets.textures.insert(texture.0, texture_handle);
                        //Problems end here
                    }
                    println!("Done getting assets");
                    commands.insert_resource(assets);
                }

Any idea what I need to change to fix this?


Solution

  • I figured out the problem.

    let texture_asset: Texture = Texture::new(Extent3d { width: 32, height: 32, depth: 1 }, TextureDimension::D2, texture.1, Rgba8UnormSrgb);

    should be

    texture_asset: Texture = Texture::new(Extent3d { width: 256, height: 256, depth: 1 }, TextureDimension::D2, texture.1, Rgba8UnormSrgb);

    The difference being that the width and height must be the same as the image you're trying to load as a Vec<u8>, I was using a test image that was 256x256 instead of the 32x32 sprites I'm going to use.