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 "] 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 [![crates.io](https://img.shields.io/crates/v/bevy_common_assets.svg)](https://crates.io/crates/bevy_common_assets) [![docs](https://docs.rs/bevy_common_assets/badge.svg)](https://docs.rs/bevy_common_assets) [![license](https://img.shields.io/crates/l/bevy_common_assets)](https://github.com/NiklasEi/bevy_common_assets#license) [![crates.io](https://img.shields.io/crates/d/bevy_common_assets.svg)](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::::new(&["level.json", "custom.json"]), RonAssetPlugin::::new(&["level.ron"]), MsgPackAssetPlugin::::new(&["level.msgpack"]), PostcardAssetPlugin::::new(&["level.postcard"]), TomlAssetPlugin::::new(&["level.toml"]), XmlAssetPlugin::::new(&["level.xml"]), YamlAssetPlugin::::new(&["level.yaml"]), CborAssetPlugin::::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 ================================================ ================================================ 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::::new(&["postlevel"]), CborAssetPlugin::::new(&["cborlevel"]), MsgPackAssetPlugin::::new(&["msglevel"]), RonAssetPlugin::::new(&["ronlevel"]), JsonAssetPlugin::::new(&["jsonlevel"]), TomlAssetPlugin::::new(&["tomllevel"]), YamlAssetPlugin::::new(&["yamllevel"]), )) // JSON source → Postcard binary .register_asset_processor::, IdentityAssetTransformer, PostcardAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), PostcardAssetSaver::default(), )) // JSON source → CBOR binary .register_asset_processor::, IdentityAssetTransformer, CborAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), CborAssetSaver::default(), )) // JSON source → MessagePack binary .register_asset_processor::, IdentityAssetTransformer, MsgPackAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), MsgPackAssetSaver::default(), )) // JSON source → RON text .register_asset_processor::, IdentityAssetTransformer, RonAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), RonAssetSaver::default(), )) // RON source → JSON text (avoids a trivial JSON→JSON round-trip) .register_asset_processor::, IdentityAssetTransformer, JsonAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), JsonAssetSaver::default(), )) // JSON source → TOML text .register_asset_processor::, IdentityAssetTransformer, TomlAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), TomlAssetSaver::default(), )) // JSON source → YAML text .register_asset_processor::, IdentityAssetTransformer, YamlAssetSaver, >>(LoadTransformAndSave::new( IdentityAssetTransformer::default(), YamlAssetSaver::default(), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_trees.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, levels: Res>, mut state: ResMut>, ) { let format_offsets: [(&Handle, 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); #[derive(Resource)] struct LevelHandles { postcard: Handle, cbor: Handle, msgpack: Handle, ron: Handle, json: Handle, toml: Handle, yaml: Handle, } #[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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::cbor::CborAssetSaver>", 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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::json::JsonAssetSaver>", 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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::msgpack::MsgPackAssetSaver>", 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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::postcard::PostcardAssetSaver>", 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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::ron::RonAssetSaver>", 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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::toml::TomlAssetSaver>", 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_asset::transformer::IdentityAssetTransformer, bevy_common_assets::yaml::YamlAssetSaver>", 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::::new(&["level.cbor"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.csv"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, positions: Res>>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle>); ================================================ 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::::new(&["level.json"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.msgpack"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.ron"]), JsonAssetPlugin::::new(&["level.json"]), )) .init_state::() .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) { let json_trees: Handle = asset_server.load("trees.level.json"); let ron_trees: Handle = 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, tree: Res, mut level_assets: ResMut>, ) { 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, handles: Res, mut state: ResMut>, ) { 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); #[derive(Resource)] struct Levels(Vec>); ================================================ 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::::new(&["level.postcard"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.ron"]))) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.toml"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.xml"]))) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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, } #[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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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::::new(&["level.yaml"]), )) .init_state::() .add_systems(Startup, setup) .add_systems(Update, spawn_level.run_if(in_state(AppState::Loading))) .run(); } fn setup(mut commands: Commands, asset_server: Res) { 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, tree: Res, mut levels: ResMut>, mut state: ResMut>, ) { 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); #[derive(Resource)] struct LevelHandle(Handle); ================================================ 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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for CborAssetPlugin where for<'de> A: Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(CborAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl CborAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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), /// A [ciborium deserializing Error](ciborium::de::Error) #[error("Could not parse CBOR: {0}")] CborDeError(#[from] ciborium::de::Error), } impl AssetLoader for CborAssetLoader 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 { 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 { _marker: PhantomData, } impl Default for CborAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for CborAssetSaver { type Asset = A; type Settings = (); type OutputLoader = CborAssetLoader; type Error = CborAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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 { extensions: Vec<&'static str>, _marker: PhantomData, delimiter: u8, } impl Plugin for CsvAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::>() .register_asset_loader(CsvAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, delimiter: self.delimiter, }); } } impl CsvAssetPlugin 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::::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 { extensions: Vec<&'static str>, _marker: PhantomData, 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 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, } impl AssetLoader for CsvAssetLoader where for<'de> A: serde::Deserialize<'de> + Asset, { type Asset = LoadedCsv; type Settings = (); type Error = CsvLoaderError; async fn load( &self, reader: &mut dyn Reader, _settings: &(), _: &mut LoadContext<'_>, ) -> Result { 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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for JsonAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(JsonAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl JsonAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for JsonAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = from_slice::(&bytes)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to JSON files #[derive(TypePath)] pub struct JsonAssetSaver { _marker: PhantomData, } impl Default for JsonAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for JsonAssetSaver { type Asset = A; type Settings = (); type OutputLoader = JsonAssetLoader; type Error = JsonAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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::::new(&["level.json"]))) //! # */ //! # .add_plugins((MinimalPlugins, AssetPlugin::default())) //! # .init_asset::() //! .add_systems(Startup, load_level) //! # .add_systems(Update, stop) //! .run(); //! } //! //! fn load_level(mut commands: Commands, asset_server: Res) { //! 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); //! //! # fn stop(mut events: MessageWriter) { //! # 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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for MsgPackAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(MsgPackAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl MsgPackAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for MsgPackAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = from_slice::(&bytes)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to `MessagePack` files #[derive(TypePath)] pub struct MsgPackAssetSaver { _marker: PhantomData, } impl Default for MsgPackAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for MsgPackAssetSaver { type Asset = A; type Settings = (); type OutputLoader = MsgPackAssetLoader; type Error = MsgPackAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for PostcardAssetPlugin where for<'de> A: Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(PostcardAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl PostcardAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for PostcardAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = from_bytes::(&bytes)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to `Postcard` files #[derive(TypePath)] pub struct PostcardAssetSaver { _marker: PhantomData, } impl Default for PostcardAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for PostcardAssetSaver { type Asset = A; type Settings = (); type OutputLoader = PostcardAssetLoader; type Error = PostcardAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for RonAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(RonAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl RonAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for RonAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = from_bytes::(&bytes)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to RON files #[derive(TypePath)] pub struct RonAssetSaver { _marker: PhantomData, } impl Default for RonAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for RonAssetSaver { type Asset = A; type Settings = (); type OutputLoader = RonAssetLoader; type Error = RonAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for TomlAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(TomlAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl TomlAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for TomlAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = serde_toml::from_str::(from_utf8(&bytes)?)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to TOML files #[derive(TypePath)] pub struct TomlAssetSaver { _marker: PhantomData, } impl Default for TomlAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for TomlAssetSaver { type Asset = A; type Settings = (); type OutputLoader = TomlAssetLoader; type Error = TomlAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for XmlAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(XmlAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl XmlAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for XmlAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = from_str::(from_utf8(&bytes)?)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to XML files #[derive(TypePath)] pub struct XmlAssetSaver { _marker: PhantomData, } impl Default for XmlAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for XmlAssetSaver { type Asset = A; type Settings = (); type OutputLoader = XmlAssetLoader; type Error = XmlAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::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 { extensions: Vec<&'static str>, _marker: PhantomData, } impl Plugin for YamlAssetPlugin where for<'de> A: serde::Deserialize<'de> + Asset, { fn build(&self, app: &mut App) { app.init_asset::() .register_asset_loader(YamlAssetLoader:: { extensions: self.extensions.clone(), _marker: PhantomData, }); } } impl YamlAssetPlugin 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 { extensions: Vec<&'static str>, _marker: PhantomData, } /// 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 AssetLoader for YamlAssetLoader 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 { let mut bytes = Vec::new(); reader.read_to_end(&mut bytes).await?; let asset = from_slice::(&bytes)?; Ok(asset) } fn extensions(&self) -> &[&str] { &self.extensions } } /// Saves your asset type `A` to YAML files #[derive(TypePath)] pub struct YamlAssetSaver { _marker: PhantomData, } impl Default for YamlAssetSaver { fn default() -> Self { Self { _marker: PhantomData, } } } impl Deserialize<'de> + Serialize> AssetSaver for YamlAssetSaver { type Asset = A; type Settings = (); type OutputLoader = YamlAssetLoader; type Error = YamlAssetError; async fn save( &self, writer: &mut bevy_asset::io::Writer, asset: bevy_asset::saver::SavedAsset<'_, Self::Asset>, _settings: &Self::Settings, ) -> Result<::Settings, Self::Error> { let yaml = serde_yaml::to_string(asset.get())?; writer.write_all(yaml.as_bytes()).await?; Ok(()) } }