Repository: NiklasEi/bevy_common_assets
Branch: main
Commit: 619d20967df5
Files: 52
Total size: 83.8 KB
Directory structure:
gitextract_gvu5u9iv/
├── .github/
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── assets/
│ ├── trees.level.cbor
│ ├── trees.level.csv
│ ├── trees.level.json
│ ├── trees.level.msgpack
│ ├── trees.level.postcard
│ ├── trees.level.ron
│ ├── trees.level.toml
│ ├── trees.level.xml
│ └── trees.level.yaml
├── examples/
│ ├── asset_savers/
│ │ ├── asset_savers.rs
│ │ └── assets/
│ │ ├── tree.png.meta
│ │ ├── trees.cborlevel
│ │ ├── trees.cborlevel.meta
│ │ ├── trees.jsonlevel
│ │ ├── trees.jsonlevel.meta
│ │ ├── trees.msglevel
│ │ ├── trees.msglevel.meta
│ │ ├── trees.postlevel
│ │ ├── trees.postlevel.meta
│ │ ├── trees.ronlevel
│ │ ├── trees.ronlevel.meta
│ │ ├── trees.tomllevel
│ │ ├── trees.tomllevel.meta
│ │ ├── trees.yamllevel
│ │ └── trees.yamllevel.meta
│ ├── cbor.rs
│ ├── csv.rs
│ ├── json.rs
│ ├── msgpack.rs
│ ├── multiple_formats.rs
│ ├── postcard.rs
│ ├── ron.rs
│ ├── toml.rs
│ ├── xml.rs
│ └── yaml.rs
└── src/
├── cbor.rs
├── csv.rs
├── json.rs
├── lib.rs
├── msgpack.rs
├── postcard.rs
├── ron.rs
├── toml.rs
├── xml.rs
└── yaml.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
pull_request:
workflow_dispatch:
push:
branches:
- main
jobs:
build:
strategy:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-build-${{ matrix.toolchain }}-${{ hashFiles('**/Cargo.toml') }}
- uses: dtolnay/rust-toolchain@stable
- name: Install Bevy dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends g++ pkg-config libx11-dev libasound2-dev libudev-dev libxkbcommon-x11-0 libwayland-dev libxkbcommon-dev
if: runner.os == 'linux'
- name: Build & run tests
run: cargo test --all-features
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ubuntu-latest-cargo-build-stable-${{ hashFiles('**/Cargo.toml') }}
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- name: Install Bevy dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends g++ pkg-config libx11-dev libasound2-dev libudev-dev libxkbcommon-x11-0 libwayland-dev libxkbcommon-dev
- name: Run clippy
run: cargo clippy --all-targets --all-features -- -W clippy::doc_markdown -Dwarnings
- name: Check format
run: cargo fmt -- --check
================================================
FILE: .gitignore
================================================
target/
Cargo.lock
.idea/
imported_assets/
================================================
FILE: CHANGELOG.md
================================================
# Changelog
## v0.16.0 - 22.03.2026
- Add asset savers to all supported formats
## v0.15.0 - 14.01.2026
- Update to Bevy 0.18
- depend on Bevy subcrates
- remove default feature (accidentally was `csv`)
## v0.14.0 - 01.10.2025
- Support for CBOR files (@Kamduis in [#49](https://github.com/NiklasEi/bevy_common_assets/pull/49))
- Update to Bevy 0.17
## v0.13.0 - 26.04.2025
- Update to Bevy 0.16
- new example `asset_savers`
## v0.12.0 - 29.11.2024
- Update to Bevy 0.15
## v0.11.0 - 04.07.2024
- Update to Bevy 0.14
- Update `quick-xml` to `0.34`
- Support for [postcard](https://github.com/jamesmunns/postcard)
## v0.10.0 - 17.02.2024
- Update to Bevy 0.13
## v0.9.1 - 17.01.2024
- CsvAssetPlugin supports configuring the delimiter with `with_delimiter`
## v0.9.0 - 07.01.2024
- Add support for CSV files
## v0.8.0 - 04.11.2023
- Update to Bevy 0.12
## v0.7.0 - 10.07.2023
- Update to Bevy 0.11
## v0.6.0 - 18.03.2023
- Support for xml assets
## v0.5.0 - 06.03.2023
- Update to Bevy 0.10
- Update `ron` to 0.8 and `toml` to 0.7
## v0.4.0 - 13.11.2022
- Update to Bevy 0.9
## v0.3.0 - 30.7.2022
- Update to Bevy 0.8
## v0.2.0 - 8.5.2022
- Support MessagePack assets
================================================
FILE: Cargo.toml
================================================
[package]
name = "bevy_common_assets"
version = "0.16.0"
authors = ["Niklas Eicker <git@nikl.me>"]
edition = "2024"
license = "MIT OR Apache-2.0"
description = "Bevy plugin adding support for loading your own asset types from common file formats such as json and yaml"
repository = "https://github.com/NiklasEi/bevy_common_assets"
homepage = "https://github.com/NiklasEi/bevy_common_assets"
documentation = "https://docs.rs/bevy_common_assets"
keywords = ["bevy", "gamedev", "asset", "assets"]
categories = ["game-development"]
readme = "./README.md"
[features]
ron = ["dep:serde_ron"]
toml = ["dep:serde_toml"]
yaml = ["dep:serde_yaml"]
json = ["dep:serde_json"]
msgpack = ["dep:rmp-serde"]
xml = ["dep:quick-xml"]
csv = ["dep:csv"]
postcard = ["dep:postcard"]
cbor = ["dep:ciborium"]
[dependencies]
bevy_app = { version = "0.18.0", default-features = false }
bevy_asset = { version = "0.18.0", default-features = false }
bevy_reflect = { version = "0.18.0", default-features = false }
serde_toml = { version = "0.9", package = "toml", optional = true }
serde_ron = { version = "0.11", package = "ron", optional = true }
serde_yaml = { version = "0.9", optional = true }
serde_json = { version = "1", optional = true }
rmp-serde = { version = "1", optional = true }
csv = { version = "1", optional = true }
thiserror = "2.0"
quick-xml = { version = "0.38.3", features = ["serialize"], optional = true }
serde = { version = "1" }
anyhow = { version = "1" }
postcard = { version = "1.0", features = ["use-std"], optional = true }
ciborium = { version = "0.2.2", optional = true }
[dev-dependencies]
bevy = { version = "0.18.0", features = [
"file_watcher",
"asset_processor",
] }
serde = { version = "1" }
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[[example]]
name = "msgpack"
path = "examples/msgpack.rs"
required-features = ["msgpack"]
[[example]]
name = "postcard"
path = "examples/postcard.rs"
required-features = ["postcard"]
[[example]]
name = "ron"
path = "examples/ron.rs"
required-features = ["ron"]
[[example]]
name = "toml"
path = "examples/toml.rs"
required-features = ["toml"]
[[example]]
name = "yaml"
path = "examples/yaml.rs"
required-features = ["yaml"]
[[example]]
name = "json"
path = "examples/json.rs"
required-features = ["json"]
[[example]]
name = "xml"
path = "examples/xml.rs"
required-features = ["xml"]
[[example]]
name = "csv"
path = "examples/csv.rs"
required-features = ["csv"]
[[example]]
name = "cbor"
path = "examples/cbor.rs"
required-features = ["cbor"]
[[example]]
name = "multiple_formats"
path = "examples/multiple_formats.rs"
required-features = ["ron", "json"]
[[example]]
name = "asset_savers"
path = "examples/asset_savers/asset_savers.rs"
required-features = ["ron", "json", "postcard", "cbor", "msgpack", "toml", "yaml"]
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
================================================
FILE: LICENSE-MIT
================================================
MIT License
Copyright 2021 Niklas Eicker
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
# Bevy common assets
[](https://crates.io/crates/bevy_common_assets)
[](https://docs.rs/bevy_common_assets)
[](https://github.com/NiklasEi/bevy_common_assets#license)
[](https://crates.io/crates/bevy_common_assets)
Collection of [Bevy][bevy] plugins offering generic asset loaders and writers for common file formats.
Supported formats:
| format | feature | example |
| :--------- | :--------- | :-------------------------------------- |
| `json` | `json` | [`json.rs`](./examples/json.rs) |
| `msgpack` | `msgpack` | [`msgpack.rs`](./examples/msgpack.rs) |
| `postcard` | `postcard` | [`postcard.rs`](./examples/postcard.rs) |
| `ron` | `ron` | [`ron.rs`](./examples/ron.rs) |
| `toml` | `toml` | [`toml.rs`](./examples/toml.rs) |
| `xml` | `xml` | [`xml.rs`](./examples/xml.rs) |
| `yaml` | `yaml` | [`yaml.rs`](./examples/yaml.rs) |
| `csv` | `csv` | [`csv.rs`](./examples/csv.rs) |
| `cbor` | `cbor` | [`cbor.rs`](./examples/cbor.rs) |
## Usage
Enable the feature(s) for the format(s) that you want to use.
Define the types that you would like to load from files and derive `serde::Deserialize`, `bevy::reflect::TypePath`, and `bevy::asset::Asset` for them.
```rust
#[derive(serde::Deserialize, bevy::asset::Asset, bevy::reflect::TypePath)]
struct Level {
positions: Vec<[f32;3]>,
}
```
With the types ready, you can start adding asset plugins. Every plugin gets the asset type that it is supposed to load
as a generic parameter. You can also configure custom file endings for each plugin:
```rust no_run
use bevy::prelude::*;
use bevy_common_assets::cbor::CborAssetPlugin;
use bevy_common_assets::json::JsonAssetPlugin;
use bevy_common_assets::msgpack::MsgPackAssetPlugin;
use bevy_common_assets::postcard::PostcardAssetPlugin;
use bevy_common_assets::ron::RonAssetPlugin;
use bevy_common_assets::toml::TomlAssetPlugin;
use bevy_common_assets::xml::XmlAssetPlugin;
use bevy_common_assets::yaml::YamlAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
JsonAssetPlugin::<Level>::new(&["level.json", "custom.json"]),
RonAssetPlugin::<Level>::new(&["level.ron"]),
MsgPackAssetPlugin::<Level>::new(&["level.msgpack"]),
PostcardAssetPlugin::<Level>::new(&["level.postcard"]),
TomlAssetPlugin::<Level>::new(&["level.toml"]),
XmlAssetPlugin::<Level>::new(&["level.xml"]),
YamlAssetPlugin::<Level>::new(&["level.yaml"]),
CborAssetPlugin::<Level>::new(&["level.cbor"])
))
// ...
.run();
}
#[derive(serde::Deserialize, bevy::asset::Asset, bevy::reflect::TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
```
The example above will load `Level` structs from json files ending on `.level.json` or `.custom.json`, from
ron files ending on `.level.ron` and so on...
See the [examples](./examples) for working Bevy apps using the different formats.
## Asset savers / using the loaders in .meta files
The more involved [example `asset_savers`](./examples/asset_savers) demonstrates how you can convert a json
asset into a processed postcard asset using the `JsonAssetLoader` and `PostcardAssetSaver`.
## Compatible Bevy versions
The main branch is compatible with the latest Bevy release.
Compatibility of `bevy_common_assets` versions:
| `bevy_common_assets` | `bevy` |
| :------------------- | :----- |
| `0.15` | `0.18` |
| `0.14` | `0.17` |
| `0.13` | `0.16` |
| `0.12` | `0.15` |
| `0.11` | `0.14` |
| `0.10` | `0.13` |
| `0.8` - `0.9` | `0.12` |
| `0.7` | `0.11` |
| `0.5` - `0.6` | `0.10` |
| `0.4` | `0.9` |
| `0.3` | `0.8` |
| `0.1` - `0.2` | `0.7` |
## License
Dual-licensed under either of
- Apache License, Version 2.0, ([LICENSE-APACHE](/LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](/LICENSE-MIT) or https://opensource.org/licenses/MIT)
at your option.
## Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.
[bevy]: https://bevyengine.org/
================================================
FILE: assets/trees.level.csv
================================================
x,y,z
42.0,42.0,0.0
4.0,32.0,0.0
54.0,7.0,0.0
-61.0,4.0,0.0
-6.0,-72.0,0.0
6.0,-89.0,0.0
================================================
FILE: assets/trees.level.json
================================================
{
"positions": [
[
42.0,
42.0,
0.0
],
[
4.0,
32.0,
0.0
],
[
54.0,
7.0,
0.0
],
[
-61.0,
4.0,
0.0
],
[
-6.0,
-72.0,
0.0
],
[
6.0,
-89.0,
0.0
]
]
}
================================================
FILE: assets/trees.level.ron
================================================
(
positions: [
(142., 56., 0.),
(25., 132., 0.),
(123., 7., 0.),
(-61., 149., 0.),
(-96., -52., 0.),
(69., -189., 0.),
]
)
================================================
FILE: assets/trees.level.toml
================================================
positions = [
[42.0, 42.0, 0.0],
[4.0, 32.0, 0.0],
[54.0, 7.0, 0.0],
[-61.0, 4.0, 0.0],
[-6.0, -72.0, 0.0],
[6.0, -89.0, 0.0],
]
================================================
FILE: assets/trees.level.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<Level>
<Position x="42.0" y="42.0" z="0.0" />
<Position x="4.0" y="32.0" z="0.0" />
<Position x="54.0" y="7.0" z="0.0" />
<Position x="-61.0" y="4.0" z="0.0" />
<Position x="-6.0" y="-72.0" z="0.0" />
<Position x="6.0" y="-89.0" z="0.0" />
</Level>
================================================
FILE: assets/trees.level.yaml
================================================
positions:
- [42.0, 42.0, 0.0]
- [4.0, 32.0, 0.0]
- [54.0, 7.0, 0.0]
- [-61.0, 4.0, 0.0]
- [-6.0, -72.0, 0.0]
- [6.0, -89.0, 0.0]
================================================
FILE: examples/asset_savers/asset_savers.rs
================================================
use bevy::asset::processor::LoadTransformAndSave;
use bevy::asset::transformer::IdentityAssetTransformer;
use bevy::prelude::*;
use bevy_common_assets::cbor::{CborAssetPlugin, CborAssetSaver};
use bevy_common_assets::json::{JsonAssetLoader, JsonAssetPlugin, JsonAssetSaver};
use bevy_common_assets::msgpack::{MsgPackAssetPlugin, MsgPackAssetSaver};
use bevy_common_assets::postcard::{PostcardAssetPlugin, PostcardAssetSaver};
use bevy_common_assets::ron::{RonAssetLoader, RonAssetPlugin, RonAssetSaver};
use bevy_common_assets::toml::{TomlAssetPlugin, TomlAssetSaver};
use bevy_common_assets::yaml::{YamlAssetPlugin, YamlAssetSaver};
use serde::{Deserialize, Serialize};
/// This example processes source asset files into various binary and text formats using asset
/// savers, then loads and renders the processed assets.
///
/// When you run the example, `examples/asset_savers/imported_assets` is created and populated
/// with the processed files. Edit any source file in `examples/asset_savers/assets/` and
/// re-run to see the processor rebuild it.
///
/// Source files and their processing pipelines:
///
/// | Source file | Source format | Processed format |
/// |------------------|---------------|---------------------|
/// | trees.postlevel | JSON | Postcard (binary) |
/// | trees.cborlevel | JSON | CBOR (binary) |
/// | trees.msglevel | JSON | MessagePack (binary)|
/// | trees.ronlevel | JSON | RON |
/// | trees.jsonlevel | RON | JSON |
/// | trees.tomllevel | JSON | TOML |
/// | trees.yamllevel | JSON | YAML |
fn main() {
App::new()
.add_plugins((
DefaultPlugins.set(AssetPlugin {
mode: AssetMode::Processed,
file_path: "examples/asset_savers/assets".to_string(),
processed_file_path: "examples/asset_savers/imported_assets/Default".to_string(),
..default()
}),
// Each plugin registers the loader for the processed output extension
PostcardAssetPlugin::<Level>::new(&["postlevel"]),
CborAssetPlugin::<Level>::new(&["cborlevel"]),
MsgPackAssetPlugin::<Level>::new(&["msglevel"]),
RonAssetPlugin::<Level>::new(&["ronlevel"]),
JsonAssetPlugin::<Level>::new(&["jsonlevel"]),
TomlAssetPlugin::<Level>::new(&["tomllevel"]),
YamlAssetPlugin::<Level>::new(&["yamllevel"]),
))
// JSON source → Postcard binary
.register_asset_processor::<LoadTransformAndSave<
JsonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
PostcardAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
PostcardAssetSaver::default(),
))
// JSON source → CBOR binary
.register_asset_processor::<LoadTransformAndSave<
JsonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
CborAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
CborAssetSaver::default(),
))
// JSON source → MessagePack binary
.register_asset_processor::<LoadTransformAndSave<
JsonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
MsgPackAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
MsgPackAssetSaver::default(),
))
// JSON source → RON text
.register_asset_processor::<LoadTransformAndSave<
JsonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
RonAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
RonAssetSaver::default(),
))
// RON source → JSON text (avoids a trivial JSON→JSON round-trip)
.register_asset_processor::<LoadTransformAndSave<
RonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
JsonAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
JsonAssetSaver::default(),
))
// JSON source → TOML text
.register_asset_processor::<LoadTransformAndSave<
JsonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
TomlAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
TomlAssetSaver::default(),
))
// JSON source → YAML text
.register_asset_processor::<LoadTransformAndSave<
JsonAssetLoader<Level>,
IdentityAssetTransformer<Level>,
YamlAssetSaver<Level>,
>>(LoadTransformAndSave::new(
IdentityAssetTransformer::default(),
YamlAssetSaver::default(),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_trees.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.insert_resource(LevelHandles {
postcard: asset_server.load("trees.postlevel"),
cbor: asset_server.load("trees.cborlevel"),
msgpack: asset_server.load("trees.msglevel"),
ron: asset_server.load("trees.ronlevel"),
json: asset_server.load("trees.jsonlevel"),
toml: asset_server.load("trees.tomllevel"),
yaml: asset_server.load("trees.yamllevel"),
});
commands.insert_resource(ImageHandle(asset_server.load("tree.png")));
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_trees(
mut commands: Commands,
handles: Res<LevelHandles>,
tree: Res<ImageHandle>,
levels: Res<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
let format_offsets: [(&Handle<Level>, Vec2); 7] = [
(&handles.postcard, Vec2::new(-525., 75.)),
(&handles.cbor, Vec2::new(-175., 75.)),
(&handles.msgpack, Vec2::new(175., 75.)),
(&handles.ron, Vec2::new(525., 75.)),
(&handles.json, Vec2::new(-350., -75.)),
(&handles.toml, Vec2::new(0., -75.)),
(&handles.yaml, Vec2::new(350., -75.)),
];
for (handle, _) in &format_offsets {
if levels.get(handle.id()).is_none() {
return;
}
}
for (handle, offset) in &format_offsets {
let level = levels.get(handle.id()).unwrap();
for position in &level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(Vec3::new(
position[0] + offset.x,
position[1] + offset.y,
position[2],
)),
));
}
}
state.set(AppState::Level);
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandles {
postcard: Handle<Level>,
cbor: Handle<Level>,
msgpack: Handle<Level>,
ron: Handle<Level>,
json: Handle<Level>,
toml: Handle<Level>,
yaml: Handle<Level>,
}
#[derive(Deserialize, Serialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
================================================
FILE: examples/asset_savers/assets/tree.png.meta
================================================
(
meta_format_version: "1.0",
asset: Load(
loader: "bevy_image::image_loader::ImageLoader",
settings: (
format: FromExtension,
is_srgb: true,
sampler: Default,
asset_usage: ("MAIN_WORLD | RENDER_WORLD"),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.cborlevel
================================================
{
"positions": [
[0.0, 10.0, 0.0],
[10.0, 0.0, 0.0],
[-10.0, 0.0, 0.0],
[0.0, -10.0, 0.0]
]
}
================================================
FILE: examples/asset_savers/assets/trees.cborlevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::json::JsonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::cbor::CborAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.jsonlevel
================================================
(
positions: [
(0.0, 10.0, 0.0),
(10.0, 0.0, 0.0),
(-10.0, 0.0, 0.0),
(0.0, -10.0, 0.0),
],
)
================================================
FILE: examples/asset_savers/assets/trees.jsonlevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::ron::RonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::json::JsonAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.msglevel
================================================
{
"positions": [
[0.0, 10.0, 0.0],
[10.0, 0.0, 0.0],
[-10.0, 0.0, 0.0],
[0.0, -10.0, 0.0]
]
}
================================================
FILE: examples/asset_savers/assets/trees.msglevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::json::JsonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::msgpack::MsgPackAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.postlevel
================================================
{
"positions": [
[0.0, 10.0, 0.0],
[10.0, 0.0, 0.0],
[-10.0, 0.0, 0.0],
[0.0, -10.0, 0.0]
]
}
================================================
FILE: examples/asset_savers/assets/trees.postlevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::json::JsonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::postcard::PostcardAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.ronlevel
================================================
{
"positions": [
[0.0, 10.0, 0.0],
[10.0, 0.0, 0.0],
[-10.0, 0.0, 0.0],
[0.0, -10.0, 0.0]
]
}
================================================
FILE: examples/asset_savers/assets/trees.ronlevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::json::JsonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::ron::RonAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.tomllevel
================================================
{
"positions": [
[0.0, 10.0, 0.0],
[10.0, 0.0, 0.0],
[-10.0, 0.0, 0.0],
[0.0, -10.0, 0.0]
]
}
================================================
FILE: examples/asset_savers/assets/trees.tomllevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::json::JsonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::toml::TomlAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/asset_savers/assets/trees.yamllevel
================================================
{
"positions": [
[0.0, 10.0, 0.0],
[10.0, 0.0, 0.0],
[-10.0, 0.0, 0.0],
[0.0, -10.0, 0.0]
]
}
================================================
FILE: examples/asset_savers/assets/trees.yamllevel.meta
================================================
(
meta_format_version: "1.0",
asset: Process(
processor: "bevy_asset::processor::process::LoadTransformAndSave<bevy_common_assets::json::JsonAssetLoader<asset_savers::Level>, bevy_asset::transformer::IdentityAssetTransformer<asset_savers::Level>, bevy_common_assets::yaml::YamlAssetSaver<asset_savers::Level>>",
settings: (
loader_settings: (),
transformer_settings: (),
saver_settings: (),
),
),
)
================================================
FILE: examples/cbor.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::cbor::CborAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
CborAssetPlugin::<Level>::new(&["level.cbor"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.cbor"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/csv.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::csv::{CsvAssetPlugin, LoadedCsv};
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
CsvAssetPlugin::<TreePosition>::new(&["level.csv"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.csv"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
positions: Res<Assets<LoadedCsv<TreePosition>>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = positions.get(&level.0) {
for position in level.rows.iter() {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(Vec3::new(position.x, position.y, position.z)),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath, Debug)]
struct TreePosition {
x: f32,
y: f32,
z: f32,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<LoadedCsv<TreePosition>>);
================================================
FILE: examples/json.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::json::JsonAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
JsonAssetPlugin::<Level>::new(&["level.json"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.json"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/msgpack.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::msgpack::MsgPackAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
MsgPackAssetPlugin::<Level>::new(&["level.msgpack"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.msgpack"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/multiple_formats.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::json::JsonAssetPlugin;
use bevy_common_assets::ron::RonAssetPlugin;
fn main() {
App::new()
// You can add loaders for different asset types, but also multiple loaders for the same asset type
// The important thing is: they all need distinct extensions!
.add_plugins((
DefaultPlugins,
RonAssetPlugin::<Level>::new(&["level.ron"]),
JsonAssetPlugin::<Level>::new(&["level.json"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, check_loading.run_if(in_state(AppState::Loading)))
.add_systems(OnEnter(AppState::Level), spawn_level)
.run();
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let json_trees: Handle<Level> = asset_server.load("trees.level.json");
let ron_trees: Handle<Level> = asset_server.load("trees.level.ron");
commands.insert_resource(Levels(vec![json_trees, ron_trees]));
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
levels: Res<Levels>,
tree: Res<ImageHandle>,
mut level_assets: ResMut<Assets<Level>>,
) {
for handle in levels.0.iter() {
let level = level_assets.remove(handle).unwrap();
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
}
}
fn check_loading(
asset_server: Res<AssetServer>,
handles: Res<Levels>,
mut state: ResMut<NextState<AppState>>,
) {
for handle in &handles.0 {
if asset_server
.get_load_state(handle)
.map(|state| !state.is_loaded())
.unwrap_or(true)
{
return;
}
}
state.set(AppState::Level);
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct Levels(Vec<Handle<Level>>);
================================================
FILE: examples/postcard.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::postcard::PostcardAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
PostcardAssetPlugin::<Level>::new(&["level.postcard"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.postcard"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/ron.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::ron::RonAssetPlugin;
fn main() {
App::new()
.add_plugins((DefaultPlugins, RonAssetPlugin::<Level>::new(&["level.ron"])))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.ron"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/toml.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::toml::TomlAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
TomlAssetPlugin::<Level>::new(&["level.toml"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.toml"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/xml.rs
================================================
use bevy::math::f32::Vec3;
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::xml::XmlAssetPlugin;
fn main() {
App::new()
.add_plugins((DefaultPlugins, XmlAssetPlugin::<Level>::new(&["level.xml"])))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.xml"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(Vec3::new(position.x, position.y, position.z)),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
#[serde(rename = "Position")]
positions: Vec<Position>,
}
#[derive(serde::Deserialize)]
struct Position {
#[serde(rename = "@x")]
x: f32,
#[serde(rename = "@y")]
y: f32,
#[serde(rename = "@z")]
z: f32,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: examples/yaml.rs
================================================
use bevy::prelude::*;
use bevy::reflect::TypePath;
use bevy_common_assets::yaml::YamlAssetPlugin;
fn main() {
App::new()
.add_plugins((
DefaultPlugins,
YamlAssetPlugin::<Level>::new(&["level.yaml"]),
))
.init_state::<AppState>()
.add_systems(Startup, setup)
.add_systems(Update, spawn_level.run_if(in_state(AppState::Loading)))
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let level = LevelHandle(asset_server.load("trees.level.yaml"));
commands.insert_resource(level);
let tree = ImageHandle(asset_server.load("tree.png"));
commands.insert_resource(tree);
commands.spawn((Camera2d, Msaa::Off));
}
fn spawn_level(
mut commands: Commands,
level: Res<LevelHandle>,
tree: Res<ImageHandle>,
mut levels: ResMut<Assets<Level>>,
mut state: ResMut<NextState<AppState>>,
) {
if let Some(level) = levels.remove(level.0.id()) {
for position in level.positions {
commands.spawn((
Sprite::from_image(tree.0.clone()),
Transform::from_translation(position.into()),
));
}
state.set(AppState::Level);
}
}
#[derive(serde::Deserialize, Asset, TypePath)]
struct Level {
positions: Vec<[f32; 3]>,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
enum AppState {
#[default]
Loading,
Level,
}
#[derive(Resource)]
struct ImageHandle(Handle<Image>);
#[derive(Resource)]
struct LevelHandle(Handle<Level>);
================================================
FILE: src/cbor.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::{
Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, io::Reader, saver::AssetSaver,
};
use bevy_reflect::TypePath;
use ciborium::from_reader;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from "Concise Binary Object Representation" (CBOR) files.
pub struct CborAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for CborAssetPlugin<A>
where
for<'de> A: Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(CborAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> CborAssetPlugin<A>
where
for<'de> A: Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from CBOR files
#[derive(TypePath)]
pub struct CborAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`CborAssetLoader`] or [`CborAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum CborAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [ciborium serializing Error](ciborium::ser::Error)
#[error("Could not serialize into CBOR: {0}")]
CborSerError(#[from] ciborium::ser::Error<std::io::Error>),
/// A [ciborium deserializing Error](ciborium::de::Error)
#[error("Could not parse CBOR: {0}")]
CborDeError(#[from] ciborium::de::Error<std::io::Error>),
}
impl<A> AssetLoader for CborAssetLoader<A>
where
for<'de> A: Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = CborAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset: A = from_reader(&bytes[..])?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to `Cbor` files
#[derive(TypePath)]
pub struct CborAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for CborAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for CborAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = CborAssetLoader<A>;
type Error = CborAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let mut bytes = Vec::new();
ciborium::into_writer(&asset.get(), &mut bytes)?;
writer.write_all(&bytes).await?;
Ok(())
}
}
================================================
FILE: src/csv.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, LoadContext};
use bevy_reflect::TypePath;
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from csv files.
pub struct CsvAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
delimiter: u8,
}
impl<A> Plugin for CsvAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<LoadedCsv<A>>()
.register_asset_loader(CsvAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
delimiter: self.delimiter,
});
}
}
impl<A> CsvAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
delimiter: b',',
}
}
/// Change the delimiter used to parse the CSV file.
///
/// The default is ","
///
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_common_assets::csv::CsvAssetPlugin;
/// App::new()
/// .add_plugins(CsvAssetPlugin::<TreePosition>::new(&["some_file.csv"]).with_delimiter(b';'));
/// # #[derive(serde::Deserialize, Asset, TypePath, Debug)]
/// # struct TreePosition {
/// # x: f32,
/// # y: f32,
/// # z: f32,
/// # }
/// ```
pub fn with_delimiter(mut self, delimiter: u8) -> Self {
self.delimiter = delimiter;
self
}
}
/// Loads your asset type `A` from csv files
#[derive(TypePath)]
pub struct CsvAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
delimiter: u8,
}
/// Possible errors that can be produced by [`CsvAssetLoader`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum CsvLoaderError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [CSV Error](serde_csv::Error)
#[error("Could not parse CSV: {0}")]
CsvError(#[from] csv::Error),
}
/// Asset representing a loaded CSV file with rows deserialized to Assets of type `A`
#[derive(TypePath, Asset)]
pub struct LoadedCsv<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Handles to the Assets the were loaded from the rows of this CSV file
pub rows: Vec<A>,
}
impl<A> AssetLoader for CsvAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = LoadedCsv<A>;
type Settings = ();
type Error = CsvLoaderError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let mut reader = csv::ReaderBuilder::new()
.delimiter(self.delimiter)
.from_reader(bytes.as_slice());
let mut rows = vec![];
for row in reader.deserialize() {
rows.push(row?);
}
Ok(LoadedCsv { rows })
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
================================================
FILE: src/json.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, saver::AssetSaver};
use bevy_reflect::TypePath;
use serde::{Deserialize, Serialize};
use serde_json::from_slice;
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from json files.
pub struct JsonAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for JsonAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(JsonAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> JsonAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from json files
#[derive(TypePath)]
pub struct JsonAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`JsonAssetLoader`] or [`JsonAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum JsonAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [JSON Error](serde_json::error::Error)
#[error("Could not parse/serialize JSON: {0}")]
JsonError(#[from] serde_json::error::Error),
}
/// Deprecated alias for [`JsonAssetError`]
#[deprecated(since = "0.15.0", note = "Use JsonAssetError instead")]
pub type JsonLoaderError = JsonAssetError;
impl<A> AssetLoader for JsonAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = JsonAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = from_slice::<A>(&bytes)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to JSON files
#[derive(TypePath)]
pub struct JsonAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for JsonAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for JsonAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = JsonAssetLoader<A>;
type Error = JsonAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let bytes = serde_json::to_vec(asset.get())?;
writer.write_all(&bytes).await?;
Ok(())
}
}
================================================
FILE: src/lib.rs
================================================
//! Bevy plugin offering generic asset loaders for common file formats
//!
//! This library includes a collection of thin wrapper plugins around serde implementations for the
//! common file formats `json`, `ron`, `toml`, `yaml`, `MessagePack` and `xml`. Each plugin adds
//! an asset loader for a user type. Assets of that type will then be loaded from all files with
//! configurable extensions.
//!
//! The following example requires the `json` feature and loads a custom asset from a json file.
//! ```
//! use bevy::prelude::*;
//! use bevy::reflect::TypePath;
//! # /*
//! use bevy_common_assets::json::JsonAssetPlugin;
//! # */
//! # use bevy::app::AppExit;
//!
//! fn main() {
//! App::new()
//! # /*
//! .add_plugins((DefaultPlugins, JsonAssetPlugin::<Level>::new(&["level.json"])))
//! # */
//! # .add_plugins((MinimalPlugins, AssetPlugin::default()))
//! # .init_asset::<Level>()
//! .add_systems(Startup, load_level)
//! # .add_systems(Update, stop)
//! .run();
//! }
//!
//! fn load_level(mut commands: Commands, asset_server: Res<AssetServer>) {
//! let handle = LevelAsset(asset_server.load("trees.level.json"));
//! commands.insert_resource(handle);
//! }
//!
//! #[derive(serde::Deserialize, Asset, TypePath)]
//! struct Level {
//! positions: Vec<[f32; 3]>,
//! }
//!
//! #[derive(Resource)]
//! struct LevelAsset(Handle<Level>);
//!
//! # fn stop(mut events: MessageWriter<AppExit>) {
//! # events.write(AppExit::Success);
//! # }
//! ```
#![forbid(unsafe_code)]
#![warn(unused_imports, missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
/// Module containing a Bevy plugin to load assets from `cbor` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "cbor")))]
#[cfg(feature = "cbor")]
pub mod cbor;
/// Module containing a Bevy plugin to load assets from `csv` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "csv")))]
#[cfg(feature = "csv")]
pub mod csv;
/// Module containing a Bevy plugin to load assets from `json` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
#[cfg(feature = "json")]
pub mod json;
/// Module containing a Bevy plugin to load assets from `MessagePack` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "msgpack")))]
#[cfg(feature = "msgpack")]
pub mod msgpack;
/// Module containing a Bevy plugin to load assets from `postcard` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "postcard")))]
#[cfg(feature = "postcard")]
pub mod postcard;
/// Module containing a Bevy plugin to load assets from `ron` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "ron")))]
#[cfg(feature = "ron")]
pub mod ron;
/// Module containing a Bevy plugin to load assets from `toml` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "toml")))]
#[cfg(feature = "toml")]
pub mod toml;
/// Module containing a Bevy plugin to load assets from `xml` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "xml")))]
#[cfg(feature = "xml")]
pub mod xml;
/// Module containing a Bevy plugin to load assets from `yaml` files with custom file extensions.
#[cfg_attr(docsrs, doc(cfg(feature = "yaml")))]
#[cfg(feature = "yaml")]
pub mod yaml;
#[cfg(all(
feature = "json",
feature = "msgpack",
feature = "ron",
feature = "toml",
feature = "xml",
feature = "yaml",
feature = "csv",
feature = "postcard",
feature = "cbor",
))]
#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;
================================================
FILE: src/msgpack.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, saver::AssetSaver};
use bevy_reflect::TypePath;
use rmp_serde::from_slice;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from `MessagePack` files.
pub struct MsgPackAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for MsgPackAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(MsgPackAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> MsgPackAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from `MessagePack` files
#[derive(TypePath)]
pub struct MsgPackAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`MsgPackAssetLoader`] or [`MsgPackAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum MsgPackAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [`MessagePack` decoding Error](rmp_serde::decode::Error)
#[error("Could not parse MessagePack: {0}")]
MsgPackDecodeError(#[from] rmp_serde::decode::Error),
/// A [`MessagePack` encoding Error](rmp_serde::encode::Error)
#[error("Could not serialize MessagePack: {0}")]
MsgPackEncodeError(#[from] rmp_serde::encode::Error),
}
/// Deprecated alias for [`MsgPackAssetError`]
#[deprecated(since = "0.15.0", note = "Use MsgPackAssetError instead")]
pub type MsgPackLoaderError = MsgPackAssetError;
impl<A> AssetLoader for MsgPackAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = MsgPackAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = from_slice::<A>(&bytes)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to `MessagePack` files
#[derive(TypePath)]
pub struct MsgPackAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for MsgPackAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for MsgPackAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = MsgPackAssetLoader<A>;
type Error = MsgPackAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let bytes = rmp_serde::to_vec(asset.get())?;
writer.write_all(&bytes).await?;
Ok(())
}
}
================================================
FILE: src/postcard.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::{
Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, io::Reader, saver::AssetSaver,
};
use bevy_reflect::TypePath;
use postcard::{from_bytes, to_stdvec};
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from `Postcard` files.
pub struct PostcardAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for PostcardAssetPlugin<A>
where
for<'de> A: Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(PostcardAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> PostcardAssetPlugin<A>
where
for<'de> A: Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from `Postcard` files
#[derive(TypePath)]
pub struct PostcardAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`PostcardAssetLoader`] or [`PostcardAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum PostcardAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [Postcard Error](postcard::Error)
#[error("Could not parse Postcard: {0}")]
PostcardError(#[from] postcard::Error),
}
impl<A> AssetLoader for PostcardAssetLoader<A>
where
for<'de> A: Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = PostcardAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = from_bytes::<A>(&bytes)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to `Postcard` files
#[derive(TypePath)]
pub struct PostcardAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for PostcardAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for PostcardAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = PostcardAssetLoader<A>;
type Error = PostcardAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let bytes = to_stdvec(&asset.get())?;
writer.write_all(&bytes).await?;
Ok(())
}
}
================================================
FILE: src/ron.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, saver::AssetSaver};
use bevy_reflect::TypePath;
use serde::{Deserialize, Serialize};
use serde_ron::de::from_bytes;
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from ron files.
pub struct RonAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for RonAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(RonAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> RonAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from ron files
#[derive(TypePath)]
pub struct RonAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`RonAssetLoader`] or [`RonAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum RonAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [RON deserialization Error](serde_ron::error::SpannedError)
#[error("Could not parse RON: {0}")]
RonDeError(#[from] serde_ron::error::SpannedError),
/// A [RON serialization Error](serde_ron::Error)
#[error("Could not serialize RON: {0}")]
RonSerError(#[from] serde_ron::Error),
}
/// Deprecated alias for [`RonAssetError`]
#[deprecated(since = "0.15.0", note = "Use RonAssetError instead")]
pub type RonLoaderError = RonAssetError;
impl<A> AssetLoader for RonAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = RonAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = from_bytes::<A>(&bytes)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to RON files
#[derive(TypePath)]
pub struct RonAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for RonAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for RonAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = RonAssetLoader<A>;
type Error = RonAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let ron = serde_ron::ser::to_string(asset.get())?;
writer.write_all(ron.as_bytes()).await?;
Ok(())
}
}
================================================
FILE: src/toml.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, saver::AssetSaver};
use bevy_reflect::TypePath;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use std::str::from_utf8;
use thiserror::Error;
/// Plugin to load your asset type `A` from toml files.
pub struct TomlAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for TomlAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(TomlAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> TomlAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from toml files
#[derive(TypePath)]
pub struct TomlAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`TomlAssetLoader`] or [`TomlAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum TomlAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [conversion Error](std::str::Utf8Error)
#[error("Could not interpret as UTF-8: {0}")]
FormatError(#[from] std::str::Utf8Error),
/// A [TOML deserialization Error](serde_toml::de::Error)
#[error("Could not parse TOML: {0}")]
TomlDeError(#[from] serde_toml::de::Error),
/// A [TOML serialization Error](serde_toml::ser::Error)
#[error("Could not serialize TOML: {0}")]
TomlSerError(#[from] serde_toml::ser::Error),
}
/// Deprecated alias for [`TomlAssetError`]
#[deprecated(since = "0.15.0", note = "Use TomlAssetError instead")]
pub type TomlLoaderError = TomlAssetError;
impl<A> AssetLoader for TomlAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = TomlAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = serde_toml::from_str::<A>(from_utf8(&bytes)?)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to TOML files
#[derive(TypePath)]
pub struct TomlAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for TomlAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for TomlAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = TomlAssetLoader<A>;
type Error = TomlAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let toml = serde_toml::to_string(asset.get())?;
writer.write_all(toml.as_bytes()).await?;
Ok(())
}
}
================================================
FILE: src/xml.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, saver::AssetSaver};
use bevy_reflect::TypePath;
use quick_xml::de::from_str;
use serde::{Deserialize, Serialize};
use std::marker::PhantomData;
use std::str::from_utf8;
use thiserror::Error;
/// Plugin to load your asset type `A` from xml files.
/// Read the [`quick_xml` docs](https://docs.rs/quick-xml/latest/quick_xml/de/) for tips on deserialization.
pub struct XmlAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for XmlAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(XmlAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> XmlAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from xml files
#[derive(TypePath)]
pub struct XmlAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`XmlAssetLoader`] or [`XmlAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum XmlAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [conversion Error](std::str::Utf8Error)
#[error("Could not interpret as UTF-8: {0}")]
FormatError(#[from] std::str::Utf8Error),
/// A [XML deserialization Error](quick_xml::DeError)
#[error("Could not parse XML: {0}")]
XmlDeError(#[from] quick_xml::DeError),
/// A XML serialization error
#[error("Could not serialize XML: {0}")]
XmlSerError(String),
}
/// Deprecated alias for [`XmlAssetError`]
#[deprecated(since = "0.15.0", note = "Use XmlAssetError instead")]
pub type XmlLoaderError = XmlAssetError;
impl<A> AssetLoader for XmlAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = XmlAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = from_str::<A>(from_utf8(&bytes)?)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to XML files
#[derive(TypePath)]
pub struct XmlAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for XmlAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for XmlAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = XmlAssetLoader<A>;
type Error = XmlAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let xml = quick_xml::se::to_string(asset.get())
.map_err(|e| XmlAssetError::XmlSerError(e.to_string()))?;
writer.write_all(xml.as_bytes()).await?;
Ok(())
}
}
================================================
FILE: src/yaml.rs
================================================
use bevy_app::{App, Plugin};
use bevy_asset::io::Reader;
use bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, saver::AssetSaver};
use bevy_reflect::TypePath;
use serde::{Deserialize, Serialize};
use serde_yaml::from_slice;
use std::marker::PhantomData;
use thiserror::Error;
/// Plugin to load your asset type `A` from yaml files.
pub struct YamlAssetPlugin<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
impl<A> Plugin for YamlAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
fn build(&self, app: &mut App) {
app.init_asset::<A>()
.register_asset_loader(YamlAssetLoader::<A> {
extensions: self.extensions.clone(),
_marker: PhantomData,
});
}
}
impl<A> YamlAssetPlugin<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
/// Create a new plugin that will load assets from files with the given extensions.
pub fn new(extensions: &[&'static str]) -> Self {
Self {
extensions: extensions.to_owned(),
_marker: PhantomData,
}
}
}
/// Loads your asset type `A` from yaml files
#[derive(TypePath)]
pub struct YamlAssetLoader<A> {
extensions: Vec<&'static str>,
_marker: PhantomData<A>,
}
/// Possible errors that can be produced by [`YamlAssetLoader`] or [`YamlAssetSaver`]
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum YamlAssetError {
/// An [IO Error](std::io::Error)
#[error("Could not read the file: {0}")]
Io(#[from] std::io::Error),
/// A [YAML Error](serde_yaml::Error)
#[error("Could not parse/serialize YAML: {0}")]
YamlError(#[from] serde_yaml::Error),
}
/// Deprecated alias for [`YamlAssetError`]
#[deprecated(since = "0.15.0", note = "Use YamlAssetError instead")]
pub type YamlLoaderError = YamlAssetError;
impl<A> AssetLoader for YamlAssetLoader<A>
where
for<'de> A: serde::Deserialize<'de> + Asset,
{
type Asset = A;
type Settings = ();
type Error = YamlAssetError;
async fn load(
&self,
reader: &mut dyn Reader,
_settings: &(),
_load_context: &mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let asset = from_slice::<A>(&bytes)?;
Ok(asset)
}
fn extensions(&self) -> &[&str] {
&self.extensions
}
}
/// Saves your asset type `A` to YAML files
#[derive(TypePath)]
pub struct YamlAssetSaver<A> {
_marker: PhantomData<A>,
}
impl<A> Default for YamlAssetSaver<A> {
fn default() -> Self {
Self {
_marker: PhantomData,
}
}
}
impl<A: Asset + for<'de> Deserialize<'de> + Serialize> AssetSaver for YamlAssetSaver<A> {
type Asset = A;
type Settings = ();
type OutputLoader = YamlAssetLoader<A>;
type Error = YamlAssetError;
async fn save(
&self,
writer: &mut bevy_asset::io::Writer,
asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>,
_settings: &Self::Settings,
) -> Result<<Self::OutputLoader as AssetLoader>::Settings, Self::Error> {
let yaml = serde_yaml::to_string(asset.get())?;
writer.write_all(yaml.as_bytes()).await?;
Ok(())
}
}
gitextract_gvu5u9iv/
├── .github/
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── assets/
│ ├── trees.level.cbor
│ ├── trees.level.csv
│ ├── trees.level.json
│ ├── trees.level.msgpack
│ ├── trees.level.postcard
│ ├── trees.level.ron
│ ├── trees.level.toml
│ ├── trees.level.xml
│ └── trees.level.yaml
├── examples/
│ ├── asset_savers/
│ │ ├── asset_savers.rs
│ │ └── assets/
│ │ ├── tree.png.meta
│ │ ├── trees.cborlevel
│ │ ├── trees.cborlevel.meta
│ │ ├── trees.jsonlevel
│ │ ├── trees.jsonlevel.meta
│ │ ├── trees.msglevel
│ │ ├── trees.msglevel.meta
│ │ ├── trees.postlevel
│ │ ├── trees.postlevel.meta
│ │ ├── trees.ronlevel
│ │ ├── trees.ronlevel.meta
│ │ ├── trees.tomllevel
│ │ ├── trees.tomllevel.meta
│ │ ├── trees.yamllevel
│ │ └── trees.yamllevel.meta
│ ├── cbor.rs
│ ├── csv.rs
│ ├── json.rs
│ ├── msgpack.rs
│ ├── multiple_formats.rs
│ ├── postcard.rs
│ ├── ron.rs
│ ├── toml.rs
│ ├── xml.rs
│ └── yaml.rs
└── src/
├── cbor.rs
├── csv.rs
├── json.rs
├── lib.rs
├── msgpack.rs
├── postcard.rs
├── ron.rs
├── toml.rs
├── xml.rs
└── yaml.rs
SYMBOL INDEX (234 symbols across 21 files)
FILE: examples/asset_savers/asset_savers.rs
function main (line 31) | fn main() {
function setup (line 118) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_trees (line 132) | fn spawn_trees(
type AppState (line 173) | enum AppState {
type ImageHandle (line 180) | struct ImageHandle(Handle<Image>);
type LevelHandles (line 183) | struct LevelHandles {
type Level (line 194) | struct Level {
FILE: examples/cbor.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 25) | fn spawn_level(
type Level (line 44) | struct Level {
type AppState (line 49) | enum AppState {
type ImageHandle (line 56) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 59) | struct LevelHandle(Handle<Level>);
FILE: examples/csv.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 26) | fn spawn_level(
type TreePosition (line 46) | struct TreePosition {
type AppState (line 53) | enum AppState {
type ImageHandle (line 60) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 63) | struct LevelHandle(Handle<LoadedCsv<TreePosition>>);
FILE: examples/json.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 26) | fn spawn_level(
type Level (line 46) | struct Level {
type AppState (line 51) | enum AppState {
type ImageHandle (line 58) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 61) | struct LevelHandle(Handle<Level>);
FILE: examples/msgpack.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 26) | fn spawn_level(
type Level (line 46) | struct Level {
type AppState (line 51) | enum AppState {
type ImageHandle (line 58) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 61) | struct LevelHandle(Handle<Level>);
FILE: examples/multiple_formats.rs
function main (line 6) | fn main() {
type Level (line 23) | struct Level {
function setup (line 27) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 37) | fn spawn_level(
function check_loading (line 54) | fn check_loading(
type AppState (line 72) | enum AppState {
type ImageHandle (line 79) | struct ImageHandle(Handle<Image>);
type Levels (line 82) | struct Levels(Vec<Handle<Level>>);
FILE: examples/postcard.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 25) | fn spawn_level(
type Level (line 44) | struct Level {
type AppState (line 49) | enum AppState {
type ImageHandle (line 56) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 59) | struct LevelHandle(Handle<Level>);
FILE: examples/ron.rs
function main (line 5) | fn main() {
function setup (line 14) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 23) | fn spawn_level(
type Level (line 43) | struct Level {
type AppState (line 48) | enum AppState {
type ImageHandle (line 55) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 58) | struct LevelHandle(Handle<Level>);
FILE: examples/toml.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 26) | fn spawn_level(
type Level (line 46) | struct Level {
type AppState (line 51) | enum AppState {
type ImageHandle (line 58) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 61) | struct LevelHandle(Handle<Level>);
FILE: examples/xml.rs
function main (line 6) | fn main() {
function setup (line 15) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 24) | fn spawn_level(
type Level (line 44) | struct Level {
type Position (line 50) | struct Position {
type AppState (line 60) | enum AppState {
type ImageHandle (line 67) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 70) | struct LevelHandle(Handle<Level>);
FILE: examples/yaml.rs
function main (line 5) | fn main() {
function setup (line 17) | fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
function spawn_level (line 26) | fn spawn_level(
type Level (line 46) | struct Level {
type AppState (line 51) | enum AppState {
type ImageHandle (line 58) | struct ImageHandle(Handle<Image>);
type LevelHandle (line 61) | struct LevelHandle(Handle<Level>);
FILE: src/cbor.rs
type CborAssetPlugin (line 12) | pub struct CborAssetPlugin<A> {
method build (line 21) | fn build(&self, app: &mut App) {
function new (line 35) | pub fn new(extensions: &[&'static str]) -> Self {
type CborAssetLoader (line 45) | pub struct CborAssetLoader<A> {
type CborAssetError (line 53) | pub enum CborAssetError {
type Asset (line 71) | type Asset = A;
type Settings (line 72) | type Settings = ();
type Error (line 73) | type Error = CborAssetError;
method load (line 75) | async fn load(
method extensions (line 87) | fn extensions(&self) -> &[&str] {
type CborAssetSaver (line 94) | pub struct CborAssetSaver<A> {
method default (line 99) | fn default() -> Self {
type Asset (line 107) | type Asset = A;
type Settings (line 108) | type Settings = ();
type OutputLoader (line 109) | type OutputLoader = CborAssetLoader<A>;
type Error (line 110) | type Error = CborAssetError;
method save (line 112) | async fn save(
FILE: src/csv.rs
type CsvAssetPlugin (line 9) | pub struct CsvAssetPlugin<A> {
method build (line 19) | fn build(&self, app: &mut App) {
function new (line 34) | pub fn new(extensions: &[&'static str]) -> Self {
function with_delimiter (line 58) | pub fn with_delimiter(mut self, delimiter: u8) -> Self {
type CsvAssetLoader (line 66) | pub struct CsvAssetLoader<A> {
type CsvLoaderError (line 75) | pub enum CsvLoaderError {
type LoadedCsv (line 86) | pub struct LoadedCsv<A>
type Asset (line 98) | type Asset = LoadedCsv<A>;
type Settings (line 99) | type Settings = ();
type Error (line 100) | type Error = CsvLoaderError;
method load (line 102) | async fn load(
method extensions (line 120) | fn extensions(&self) -> &[&str] {
FILE: src/json.rs
type JsonAssetPlugin (line 11) | pub struct JsonAssetPlugin<A> {
method build (line 20) | fn build(&self, app: &mut App) {
function new (line 34) | pub fn new(extensions: &[&'static str]) -> Self {
type JsonAssetLoader (line 44) | pub struct JsonAssetLoader<A> {
type JsonAssetError (line 52) | pub enum JsonAssetError {
type JsonLoaderError (line 63) | pub type JsonLoaderError = JsonAssetError;
type Asset (line 69) | type Asset = A;
type Settings (line 70) | type Settings = ();
type Error (line 71) | type Error = JsonAssetError;
method load (line 73) | async fn load(
method extensions (line 85) | fn extensions(&self) -> &[&str] {
type JsonAssetSaver (line 92) | pub struct JsonAssetSaver<A> {
method default (line 97) | fn default() -> Self {
type Asset (line 105) | type Asset = A;
type Settings (line 106) | type Settings = ();
type OutputLoader (line 107) | type OutputLoader = JsonAssetLoader<A>;
type Error (line 108) | type Error = JsonAssetError;
method save (line 110) | async fn save(
FILE: src/lib.rs
type ReadmeDoctests (line 101) | pub struct ReadmeDoctests;
FILE: src/msgpack.rs
type MsgPackAssetPlugin (line 11) | pub struct MsgPackAssetPlugin<A> {
method build (line 20) | fn build(&self, app: &mut App) {
function new (line 34) | pub fn new(extensions: &[&'static str]) -> Self {
type MsgPackAssetLoader (line 44) | pub struct MsgPackAssetLoader<A> {
type MsgPackAssetError (line 52) | pub enum MsgPackAssetError {
type MsgPackLoaderError (line 66) | pub type MsgPackLoaderError = MsgPackAssetError;
type Asset (line 72) | type Asset = A;
type Settings (line 73) | type Settings = ();
type Error (line 74) | type Error = MsgPackAssetError;
method load (line 76) | async fn load(
method extensions (line 88) | fn extensions(&self) -> &[&str] {
type MsgPackAssetSaver (line 95) | pub struct MsgPackAssetSaver<A> {
method default (line 100) | fn default() -> Self {
type Asset (line 108) | type Asset = A;
type Settings (line 109) | type Settings = ();
type OutputLoader (line 110) | type OutputLoader = MsgPackAssetLoader<A>;
type Error (line 111) | type Error = MsgPackAssetError;
method save (line 113) | async fn save(
FILE: src/postcard.rs
type PostcardAssetPlugin (line 12) | pub struct PostcardAssetPlugin<A> {
method build (line 21) | fn build(&self, app: &mut App) {
function new (line 35) | pub fn new(extensions: &[&'static str]) -> Self {
type PostcardAssetLoader (line 45) | pub struct PostcardAssetLoader<A> {
type PostcardAssetError (line 53) | pub enum PostcardAssetError {
type Asset (line 66) | type Asset = A;
type Settings (line 67) | type Settings = ();
type Error (line 68) | type Error = PostcardAssetError;
method load (line 70) | async fn load(
method extensions (line 82) | fn extensions(&self) -> &[&str] {
type PostcardAssetSaver (line 89) | pub struct PostcardAssetSaver<A> {
method default (line 94) | fn default() -> Self {
type Asset (line 102) | type Asset = A;
type Settings (line 103) | type Settings = ();
type OutputLoader (line 104) | type OutputLoader = PostcardAssetLoader<A>;
type Error (line 105) | type Error = PostcardAssetError;
method save (line 107) | async fn save(
FILE: src/ron.rs
type RonAssetPlugin (line 11) | pub struct RonAssetPlugin<A> {
method build (line 20) | fn build(&self, app: &mut App) {
function new (line 34) | pub fn new(extensions: &[&'static str]) -> Self {
type RonAssetLoader (line 44) | pub struct RonAssetLoader<A> {
type RonAssetError (line 52) | pub enum RonAssetError {
type RonLoaderError (line 66) | pub type RonLoaderError = RonAssetError;
type Asset (line 72) | type Asset = A;
type Settings (line 73) | type Settings = ();
type Error (line 74) | type Error = RonAssetError;
method load (line 76) | async fn load(
method extensions (line 88) | fn extensions(&self) -> &[&str] {
type RonAssetSaver (line 95) | pub struct RonAssetSaver<A> {
method default (line 100) | fn default() -> Self {
type Asset (line 108) | type Asset = A;
type Settings (line 109) | type Settings = ();
type OutputLoader (line 110) | type OutputLoader = RonAssetLoader<A>;
type Error (line 111) | type Error = RonAssetError;
method save (line 113) | async fn save(
FILE: src/toml.rs
type TomlAssetPlugin (line 11) | pub struct TomlAssetPlugin<A> {
method build (line 20) | fn build(&self, app: &mut App) {
function new (line 34) | pub fn new(extensions: &[&'static str]) -> Self {
type TomlAssetLoader (line 44) | pub struct TomlAssetLoader<A> {
type TomlAssetError (line 52) | pub enum TomlAssetError {
type TomlLoaderError (line 69) | pub type TomlLoaderError = TomlAssetError;
type Asset (line 75) | type Asset = A;
type Settings (line 76) | type Settings = ();
type Error (line 77) | type Error = TomlAssetError;
method load (line 79) | async fn load(
method extensions (line 91) | fn extensions(&self) -> &[&str] {
type TomlAssetSaver (line 98) | pub struct TomlAssetSaver<A> {
method default (line 103) | fn default() -> Self {
type Asset (line 111) | type Asset = A;
type Settings (line 112) | type Settings = ();
type OutputLoader (line 113) | type OutputLoader = TomlAssetLoader<A>;
type Error (line 114) | type Error = TomlAssetError;
method save (line 116) | async fn save(
FILE: src/xml.rs
type XmlAssetPlugin (line 13) | pub struct XmlAssetPlugin<A> {
method build (line 22) | fn build(&self, app: &mut App) {
function new (line 36) | pub fn new(extensions: &[&'static str]) -> Self {
type XmlAssetLoader (line 46) | pub struct XmlAssetLoader<A> {
type XmlAssetError (line 54) | pub enum XmlAssetError {
type XmlLoaderError (line 71) | pub type XmlLoaderError = XmlAssetError;
type Asset (line 77) | type Asset = A;
type Settings (line 78) | type Settings = ();
type Error (line 79) | type Error = XmlAssetError;
method load (line 81) | async fn load(
method extensions (line 93) | fn extensions(&self) -> &[&str] {
type XmlAssetSaver (line 100) | pub struct XmlAssetSaver<A> {
method default (line 105) | fn default() -> Self {
type Asset (line 113) | type Asset = A;
type Settings (line 114) | type Settings = ();
type OutputLoader (line 115) | type OutputLoader = XmlAssetLoader<A>;
type Error (line 116) | type Error = XmlAssetError;
method save (line 118) | async fn save(
FILE: src/yaml.rs
type YamlAssetPlugin (line 11) | pub struct YamlAssetPlugin<A> {
method build (line 20) | fn build(&self, app: &mut App) {
function new (line 34) | pub fn new(extensions: &[&'static str]) -> Self {
type YamlAssetLoader (line 44) | pub struct YamlAssetLoader<A> {
type YamlAssetError (line 52) | pub enum YamlAssetError {
type YamlLoaderError (line 63) | pub type YamlLoaderError = YamlAssetError;
type Asset (line 69) | type Asset = A;
type Settings (line 70) | type Settings = ();
type Error (line 71) | type Error = YamlAssetError;
method load (line 73) | async fn load(
method extensions (line 85) | fn extensions(&self) -> &[&str] {
type YamlAssetSaver (line 92) | pub struct YamlAssetSaver<A> {
method default (line 97) | fn default() -> Self {
type Asset (line 105) | type Asset = A;
type Settings (line 106) | type Settings = ();
type OutputLoader (line 107) | type OutputLoader = YamlAssetLoader<A>;
type Error (line 108) | type Error = YamlAssetError;
method save (line 110) | async fn save(
Condensed preview — 52 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (92K chars).
[
{
"path": ".github/workflows/ci.yml",
"chars": 1820,
"preview": "name: CI\n\non:\n pull_request:\n workflow_dispatch:\n push:\n branches:\n - main\n\njobs:\n build:\n strategy:\n "
},
{
"path": ".gitignore",
"chars": 44,
"preview": "target/\nCargo.lock\n.idea/\n\nimported_assets/\n"
},
{
"path": "CHANGELOG.md",
"chars": 1183,
"preview": "# Changelog\n\n## v0.16.0 - 22.03.2026\n- Add asset savers to all supported formats\n\n## v0.15.0 - 14.01.2026\n- Update to Be"
},
{
"path": "Cargo.toml",
"chars": 2827,
"preview": "[package]\nname = \"bevy_common_assets\"\nversion = \"0.16.0\"\nauthors = [\"Niklas Eicker <git@nikl.me>\"]\nedition = \"2024\"\nlice"
},
{
"path": "LICENSE-APACHE",
"chars": 9647,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "LICENSE-MIT",
"chars": 1066,
"preview": "MIT License\n\nCopyright 2021 Niklas Eicker\n\nPermission is hereby granted, free of charge, to any person obtaining a copy "
},
{
"path": "README.md",
"chars": 4748,
"preview": "# Bevy common assets\n\n[](https://crates.io/crates/be"
},
{
"path": "assets/trees.level.csv",
"chars": 89,
"preview": "x,y,z\n42.0,42.0,0.0\n4.0,32.0,0.0\n54.0,7.0,0.0\n-61.0,4.0,0.0\n-6.0,-72.0,0.0\n6.0,-89.0,0.0\n"
},
{
"path": "assets/trees.level.json",
"chars": 305,
"preview": "{\n \"positions\": [\n [\n 42.0,\n 42.0,\n 0.0\n ],\n [\n 4.0,\n 32.0,\n 0.0\n ],\n [\n "
},
{
"path": "assets/trees.level.ron",
"chars": 179,
"preview": "(\n positions: [\n (142., 56., 0.),\n (25., 132., 0.),\n (123., 7., 0.),\n (-61., 149., 0.),\n "
},
{
"path": "assets/trees.level.toml",
"chars": 153,
"preview": "positions = [\n [42.0, 42.0, 0.0],\n [4.0, 32.0, 0.0],\n [54.0, 7.0, 0.0],\n [-61.0, 4.0, 0.0],\n [-6.0, -72.0"
},
{
"path": "assets/trees.level.xml",
"chars": 301,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Level>\n <Position x=\"42.0\" y=\"42.0\" z=\"0.0\" />\n <Position x=\"4.0\" y=\"32.0\" z=\""
},
{
"path": "assets/trees.level.yaml",
"chars": 142,
"preview": "positions:\n - [42.0, 42.0, 0.0]\n - [4.0, 32.0, 0.0]\n - [54.0, 7.0, 0.0]\n - [-61.0, 4.0, 0.0]\n - [-6.0, -72.0, 0.0]\n"
},
{
"path": "examples/asset_savers/asset_savers.rs",
"chars": 7514,
"preview": "use bevy::asset::processor::LoadTransformAndSave;\nuse bevy::asset::transformer::IdentityAssetTransformer;\nuse bevy::prel"
},
{
"path": "examples/asset_savers/assets/tree.png.meta",
"chars": 295,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Load(\n loader: \"bevy_image::image_loader::ImageLoader\",\n sett"
},
{
"path": "examples/asset_savers/assets/trees.cborlevel",
"chars": 114,
"preview": "{\n \"positions\": [\n [0.0, 10.0, 0.0],\n [10.0, 0.0, 0.0],\n [-10.0, 0.0, 0.0],\n [0.0, -10.0, 0.0]\n ]\n}\n"
},
{
"path": "examples/asset_savers/assets/trees.cborlevel.meta",
"chars": 471,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/asset_savers/assets/trees.jsonlevel",
"chars": 134,
"preview": "(\n positions: [\n (0.0, 10.0, 0.0),\n (10.0, 0.0, 0.0),\n (-10.0, 0.0, 0.0),\n (0.0, -10.0, 0"
},
{
"path": "examples/asset_savers/assets/trees.jsonlevel.meta",
"chars": 469,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/asset_savers/assets/trees.msglevel",
"chars": 114,
"preview": "{\n \"positions\": [\n [0.0, 10.0, 0.0],\n [10.0, 0.0, 0.0],\n [-10.0, 0.0, 0.0],\n [0.0, -10.0, 0.0]\n ]\n}\n"
},
{
"path": "examples/asset_savers/assets/trees.msglevel.meta",
"chars": 477,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/asset_savers/assets/trees.postlevel",
"chars": 114,
"preview": "{\n \"positions\": [\n [0.0, 10.0, 0.0],\n [10.0, 0.0, 0.0],\n [-10.0, 0.0, 0.0],\n [0.0, -10.0, 0.0]\n ]\n}\n"
},
{
"path": "examples/asset_savers/assets/trees.postlevel.meta",
"chars": 479,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/asset_savers/assets/trees.ronlevel",
"chars": 114,
"preview": "{\n \"positions\": [\n [0.0, 10.0, 0.0],\n [10.0, 0.0, 0.0],\n [-10.0, 0.0, 0.0],\n [0.0, -10.0, 0.0]\n ]\n}\n"
},
{
"path": "examples/asset_savers/assets/trees.ronlevel.meta",
"chars": 469,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/asset_savers/assets/trees.tomllevel",
"chars": 114,
"preview": "{\n \"positions\": [\n [0.0, 10.0, 0.0],\n [10.0, 0.0, 0.0],\n [-10.0, 0.0, 0.0],\n [0.0, -10.0, 0.0]\n ]\n}\n"
},
{
"path": "examples/asset_savers/assets/trees.tomllevel.meta",
"chars": 471,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/asset_savers/assets/trees.yamllevel",
"chars": 114,
"preview": "{\n \"positions\": [\n [0.0, 10.0, 0.0],\n [10.0, 0.0, 0.0],\n [-10.0, 0.0, 0.0],\n [0.0, -10.0, 0.0]\n ]\n}\n"
},
{
"path": "examples/asset_savers/assets/trees.yamllevel.meta",
"chars": 471,
"preview": "(\n meta_format_version: \"1.0\",\n asset: Process(\n processor: \"bevy_asset::processor::process::LoadTransformA"
},
{
"path": "examples/cbor.rs",
"chars": 1560,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::cbor::CborAssetPlugin;\n\nfn main() {\n App::"
},
{
"path": "examples/csv.rs",
"chars": 1657,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::csv::{CsvAssetPlugin, LoadedCsv};\n\nfn main() "
},
{
"path": "examples/json.rs",
"chars": 1562,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::json::JsonAssetPlugin;\n\nfn main() {\n App::"
},
{
"path": "examples/msgpack.rs",
"chars": 1577,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::msgpack::MsgPackAssetPlugin;\n\nfn main() {\n "
},
{
"path": "examples/multiple_formats.rs",
"chars": 2349,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::json::JsonAssetPlugin;\nuse bevy_common_assets"
},
{
"path": "examples/postcard.rs",
"chars": 1580,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::postcard::PostcardAssetPlugin;\n\nfn main() {\n "
},
{
"path": "examples/ron.rs",
"chars": 1522,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::ron::RonAssetPlugin;\n\nfn main() {\n App::ne"
},
{
"path": "examples/toml.rs",
"chars": 1562,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::toml::TomlAssetPlugin;\n\nfn main() {\n App::"
},
{
"path": "examples/xml.rs",
"chars": 1784,
"preview": "use bevy::math::f32::Vec3;\nuse bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::xml::XmlAssetPlugi"
},
{
"path": "examples/yaml.rs",
"chars": 1562,
"preview": "use bevy::prelude::*;\nuse bevy::reflect::TypePath;\nuse bevy_common_assets::yaml::YamlAssetPlugin;\n\nfn main() {\n App::"
},
{
"path": "src/cbor.rs",
"chars": 3398,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::{\n Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, io::Reader,"
},
{
"path": "src/csv.rs",
"chars": 3395,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, LoadContext};\nus"
},
{
"path": "src/json.rs",
"chars": 3306,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, L"
},
{
"path": "src/lib.rs",
"chars": 3608,
"preview": "//! Bevy plugin offering generic asset loaders for common file formats\n//!\n//! This library includes a collection of thi"
},
{
"path": "src/msgpack.rs",
"chars": 3590,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, L"
},
{
"path": "src/postcard.rs",
"chars": 3184,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::{\n Asset, AssetApp, AssetLoader, AsyncWriteExt, LoadContext, io::Reader,"
},
{
"path": "src/ron.rs",
"chars": 3459,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, L"
},
{
"path": "src/toml.rs",
"chars": 3641,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, L"
},
{
"path": "src/xml.rs",
"chars": 3752,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, L"
},
{
"path": "src/yaml.rs",
"chars": 3303,
"preview": "use bevy_app::{App, Plugin};\nuse bevy_asset::io::Reader;\nuse bevy_asset::{Asset, AssetApp, AssetLoader, AsyncWriteExt, L"
}
]
// ... and 3 more files (download for full content)
About this extraction
This page contains the full source code of the NiklasEi/bevy_common_assets GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 52 files (83.8 KB), approximately 23.4k tokens, and a symbol index with 234 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.