如何在紫水晶引擎中从内存中加载纹理?

How to load a texture from memory in amethyst engine?

我已经阅读了官方文档,但找不到任何直接从内存加载纹理的方法。它目前确实具有从文件加载纹理的 API,但我真正想要的是从 &[u8] 加载纹理,它表示具有固定大小的 RGBA 格式图像。

offical tutorial

中略微提到了一个解决方案
//To load a texture in memory, you can't use [0.; 4].into() as the TextureData anymore. 
// Use:
use amethyst::{
    assets::{AssetStorage, Handle, Loader, Prefab, PrefabLoader},
    ecs::World,
    renderer::{
        loaders::load_from_srgba,
        palette::Srgba,
        types::TextureData,
        Texture,
    },
};

let loader = world.read_resource::<Loader>();
let texture_assets = world.read_resource::<AssetStorage<Texture>>();
let texture_builder = load_from_srgba(Srgba::new(0., 0., 0., 0.));
let texture_handle: Handle<Texture> =
loader.load_from_data(TextureData::from(texture_builder), (), &texture_assets);

另一种方式在Doc of ImageFormat中介绍。

let loader = res.fetch_mut::<Loader>();
let texture_storage = res.fetch_mut::<AssetStorage<Texture>>();

let texture_builder = TextureBuilder::new()
    .with_data_width(handle.width)
    .with_data_height(handle.height)
    .with_kind(image::Kind::D2(handle.width, handle.height, 1, 1))
    .with_view_kind(image::ViewKind::D2)
    .with_sampler_info(SamplerInfo {
        min_filter: Filter::Linear,
        mag_filter: Filter::Linear,
        mip_filter: Filter::Linear,
        wrap_mode: (WrapMode::Clamp, WrapMode::Clamp, WrapMode::Clamp),
        lod_bias: 0.0.into(),
        lod_range: std::ops::Range {
            start: 0.0.into(),
            end: 1000.0.into(),
        },
        comparison: None,
        border: PackedColor(0),
        anisotropic: Anisotropic::Off,
    })
    .with_raw_data(handle.pixels, Format::Rgba8Unorm);

let tex: Handle<Texture> = loader.load_from_data(TextureData(texture_builder), (), &texture_storage);

For the version above 0.12, you have to warp the Handle<Texture> into a SpriteRender to display it.