Upgrade to Bevy 0.19 and harden editor workflows
CI / Format, lint, test, build (push) Has been cancelled

This commit is contained in:
Rbanh committed 2026-07-09 23:43:47 -04:00
1 parent 3f85d25cc7
commit b5e561904c
204 files changed
+6972 -29907

No files matched your search

+1
View File
@@ -0,0 +1 @@
{"v":1}
+6
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "76957e35dc448209886cd0977ab7f893e0de12c3"
},
"path_in_vcs": ""
}
@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "cargo" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
+107
View File
@@ -0,0 +1,107 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
CARGO_TERM_COLOR: always
# Keep binaries small.
RUSTFLAGS: "-C debuginfo=0"
jobs:
# ── Fast compile check ────────────────────────────────────────────────────
check:
name: Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust (stable)
uses: dtolnay/rust-toolchain@stable
- name: Cache Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-check-${{ hashFiles('**/Cargo.toml') }}
restore-keys: |
${{ runner.os }}-cargo-check-
${{ runner.os }}-cargo-
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libasound2-dev \
libudev-dev \
libwayland-dev \
libxkbcommon-dev
- name: Check crate
run: cargo check
- name: Check examples
run: cargo check --examples
- name: Check tests
run: cargo test --no-run
# ── Unit & integration tests ──────────────────────────────────────────────
test:
name: Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust (stable)
uses: dtolnay/rust-toolchain@stable
- name: Cache Cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-test-${{ hashFiles('**/Cargo.toml') }}
restore-keys: |
${{ runner.os }}-cargo-test-
${{ runner.os }}-cargo-
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libasound2-dev \
libudev-dev \
libwayland-dev \
libxkbcommon-dev
# Sparse-clone only the data/ directory from ufbx/ufbx.
# --filter=blob:none skips downloading blobs during the initial clone;
# they are fetched on demand when the sparse checkout is materialised.
- name: Clone ufbx test data
run: |
git clone \
--filter=blob:none \
--sparse \
--depth 1 \
https://github.com/ufbx/ufbx.git \
/tmp/ufbx
cd /tmp/ufbx
git sparse-checkout set data
- name: Run tests
env:
UFBX_TEST_DATA: /tmp/ufbx/data
run: cargo test -- --nocapture
+24
View File
@@ -0,0 +1,24 @@
# Generated by Cargo
# will have compiled files and executables
debug/
target/
/target
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# Generated by cargo mutants
# Contains mutation testing data
**/mutants.out*/
# RustRover
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
Cargo.lock
+109
View File
@@ -0,0 +1,109 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
name = "bevy_ufbx"
version = "0.18.1-rc.1"
authors = ["Artur <arturmisiurev@gmail.com>"]
build = false
exclude = ["assets/"]
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "FBX asset loader for Bevy using the ufbx library"
readme = "README.md"
keywords = [
"bevy",
"fbx",
"asset",
"loader",
]
categories = [
"game-development",
"graphics",
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/FizzWizzleDazzle/bevy_ufbx"
[lib]
name = "bevy_ufbx"
path = "src/lib.rs"
[[example]]
name = "load_fbx"
path = "examples/load_fbx.rs"
[[test]]
name = "basic_loading"
path = "tests/basic_loading.rs"
[[test]]
name = "integration"
path = "tests/integration.rs"
[[test]]
name = "label"
path = "tests/label.rs"
[[test]]
name = "load_all_ufbx_data"
path = "tests/load_all_ufbx_data.rs"
[[test]]
name = "loader_settings"
path = "tests/loader_settings.rs"
[[test]]
name = "types"
path = "tests/types.rs"
[[test]]
name = "utils"
path = "tests/utils.rs"
[dependencies.bevy]
version = "0.19"
features = [
"bevy_asset",
"bevy_render",
"bevy_pbr",
"bevy_world_serialization",
]
default-features = false
[dependencies.bevy_image]
version = "0.19"
[dependencies.bevy_material]
version = "0.19"
[dependencies.serde]
version = "1.0"
features = ["derive"]
[dependencies.thiserror]
version = "2.0"
[dependencies.ufbx]
version = "0.9"
[dev-dependencies.bevy]
version = "0.19"
default-features = true
[dev-dependencies.serde_json]
version = "1.0.145"
[dev-dependencies.ufbx]
version = "0.9"
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "bevy_ufbx"
version = "0.18.1-rc.1"
edition = "2024"
authors = ["Artur <arturmisiurev@gmail.com>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/FizzWizzleDazzle/bevy_ufbx"
description = "FBX asset loader for Bevy using the ufbx library"
keywords = ["bevy", "fbx", "asset", "loader"]
categories = ["game-development", "graphics"]
exclude = ["assets/"]
[dependencies]
bevy = { version = "0.19", default-features = false, features = [
"bevy_asset",
"bevy_render",
"bevy_pbr",
"bevy_world_serialization",
]}
bevy_image = "0.19"
bevy_material = "0.19"
ufbx = "0.9"
thiserror = "2.0"
serde = { version = "1.0", features = ["derive"] }
[dev-dependencies]
bevy = { version = "0.19", default-features = true }
serde_json = "1.0.145"
ufbx = "0.9"
+201
View File
@@ -0,0 +1,201 @@
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 FizzWizZleDazzle
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.
+112
View File
@@ -0,0 +1,112 @@
# bevy_ufbx
FBX asset loader for [Bevy](https://bevyengine.org) powered by [ufbx](https://github.com/ufbx/ufbx).
## Bevy compatibility
| bevy | bevy_ufbx |
|------|-----------|
| 0.18 | 0.18 |
| 0.17 | 0.17 |
## Installation
```toml
[dependencies]
bevy = "0.18"
bevy_ufbx = "0.18"
```
## Quick start
```rust
use bevy::prelude::*;
use bevy_ufbx::FbxPlugin;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(FbxPlugin)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera3d::default());
commands.spawn(SceneRoot(
asset_server.load("character.fbx#Scene0"),
));
}
```
## Loading with custom settings
```rust
use bevy_ufbx::{Fbx, FbxLoaderSettings};
fn setup(asset_server: Res<AssetServer>) {
asset_server.load_with_settings::<Fbx, FbxLoaderSettings>(
"environment.fbx",
|s| {
s.load_cameras = false;
s.load_lights = false;
},
);
}
```
### `FbxLoaderSettings` fields
| Field | Type | Default | Description |
|----------------------|----------------------|-------------------------------|---------------------------------------------|
| `load_meshes` | `RenderAssetUsages` | `RenderAssetUsages::default()` | Which worlds the mesh is available in |
| `load_materials` | `RenderAssetUsages` | `RenderAssetUsages::default()` | Which worlds the material is available in |
| `load_cameras` | `bool` | `true` | Import cameras from the FBX |
| `load_lights` | `bool` | `true` | Import lights from the FBX |
| `include_source` | `bool` | `false` | Keep raw bytes in the loaded asset |
| `convert_coordinates`| `bool` | `false` | Remap axes to Bevy's right-handed Y-up space|
## Asset labels
Individual sub-assets can be addressed with `#Label` path suffixes:
| Label | Type | Description |
|-------------------|---------------------|-----------------------------------------|
| `Scene{N}` | `Scene` | Scene hierarchy (N = scene index) |
| `Mesh{N}` | `Mesh` | Triangulated mesh |
| `Material{N}` | `StandardMaterial` | PBR material |
| `Node{N}` | `FbxNode` | Transform node |
| `Skin{N}` | `FbxSkin` | Skeletal skin |
| `DefaultMaterial` | `StandardMaterial` | Fallback material when none is present |
```rust
let scene = asset_server.load::<Scene>("model.fbx#Scene0");
let mesh = asset_server.load::<Mesh>("model.fbx#Mesh0");
let material = asset_server.load::<StandardMaterial>("model.fbx#Material0");
```
## Supported features
- Triangle meshes with positions, normals, and UVs
- Multi-material meshes (face groups per material)
- PBR materials (base color, metallic, roughness, normal, emission, AO)
- Texture mapping, including `.fbm` embedded texture folders
- Skeletal skinning data (bone weights / bind poses)
- Scene hierarchy (node transforms)
- Directional, point, and spot lights
## Limitations
- Animation curves are parsed but **not yet forwarded to Bevy's animation system**
- Cameras are not imported into Bevy camera components
- NURBS and subdivision surfaces are not supported (ufbx triangulates on load)
## Example
```sh
cargo run --example load_fbx -- my_model.fbx
```
## License
Licensed under either of [MIT](LICENSE-MIT) or [Apache 2.0](LICENSE-APACHE) at your option.
+92
View File
@@ -0,0 +1,92 @@
//! Loads and displays an FBX file.
//!
//! Pass a path (relative to the `assets/` directory) as the first argument,
//! or drop a `cube.fbx` into `assets/` and run without arguments:
//!
//! ```sh
//! cargo run --example load_fbx -- spider.fbx
//! ```
//!
//! The loaded model spins slowly so you can inspect it from all sides.
//! Use `FbxLoaderSettings` to control what gets imported – see the
//! `load_with_settings` section at the bottom of `setup`.
use bevy::prelude::*;
use bevy_ufbx::{Fbx, FbxLoaderSettings, FbxPlugin};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(FbxPlugin)
.add_systems(Startup, setup)
.add_systems(Update, rotate)
.run();
}
// ── Components / resources ──────────────────────────────────────────────────
#[derive(Component)]
struct Spinning;
#[derive(Resource)]
struct FbxHandle(Handle<Fbx>);
// ── Setup ───────────────────────────────────────────────────────────────────
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// ── Camera ──────────────────────────────────────────────────────────────
commands.spawn((
Camera3d::default(),
Transform::from_xyz(4.0, 4.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
));
// ── Lighting ─────────────────────────────────────────────────────────────
commands.spawn((
DirectionalLight {
illuminance: 10_000.0,
shadows_enabled: true,
..default()
},
Transform::from_rotation(Quat::from_euler(
EulerRot::XYZ,
-45_f32.to_radians(),
45_f32.to_radians(),
0.0,
)),
));
commands.insert_resource(GlobalAmbientLight {
color: Color::WHITE,
brightness: 200.0,
affects_lightmapped_meshes: false,
});
// ── FBX path from CLI args (defaults to "cube.fbx") ──────────────────────
let path = std::env::args()
.nth(1)
.unwrap_or_else(|| "cube.fbx".to_string());
// --- Default loading ---
let scene = asset_server.load(format!("{path}#Scene0"));
commands.spawn((SceneRoot(scene), Spinning));
// --- Custom settings (uncomment to use instead) ---
// let fbx = asset_server.load_with_settings::<Fbx, FbxLoaderSettings>(
// path.clone(),
// |s| {
// s.load_cameras = false;
// s.load_lights = false;
// },
// );
// commands.insert_resource(FbxHandle(fbx));
info!("Loading '{path}' …");
}
// ── Systems ──────────────────────────────────────────────────────────────────
fn rotate(time: Res<Time>, mut q: Query<&mut Transform, With<Spinning>>) {
for mut t in &mut q {
t.rotate_y(time.delta_secs() * 0.4);
}
}
+28
View File
@@ -0,0 +1,28 @@
use thiserror::Error;
#[derive(Error, Debug)]
pub enum FbxError {
#[error("Failed to read FBX file: {0}")]
Io(#[from] std::io::Error),
#[error("Failed to load FBX: {0}")]
UfbxError(String),
#[error("Failed to convert FBX data: {0}")]
ConversionError(String),
#[error("Failed to convert mesh: {0}")]
MeshConversion(String),
#[error("Failed to convert material: {0}")]
MaterialConversion(String),
#[error("Failed to load texture: {0}")]
TextureLoad(String),
#[error("Invalid FBX data: {0}")]
InvalidData(String),
#[error("Unsupported FBX feature: {0}")]
UnsupportedFeature(String),
}
+63
View File
@@ -0,0 +1,63 @@
//! Labels that can be used to load part of an FBX asset
use bevy::asset::AssetPath;
/// Labels that can be used to load part of an FBX asset
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxAssetLabel {
/// `Scene{}`: FBX Scene as a Bevy [`Scene`](bevy::scene::Scene)
Scene(usize),
/// `Mesh{}`: FBX Mesh as a Bevy [`Mesh`](bevy::render::mesh::Mesh)
Mesh(usize),
/// `Material{}`: FBX material as a Bevy [`StandardMaterial`](bevy::pbr::StandardMaterial)
Material(usize),
/// `Animation{}`: FBX animation as a Bevy [`AnimationClip`](bevy::animation::AnimationClip)
Animation(usize),
/// `AnimationStack{}`: FBX animation stack with multiple layers
AnimationStack(usize),
/// `Skeleton{}`: FBX skeleton for skeletal animation
Skeleton(usize),
/// `Node{}`: Individual FBX node in the scene hierarchy
Node(usize),
/// `Skin{}`: FBX skin for skeletal animation
Skin(usize),
/// `Light{}`: FBX light definition
Light(usize),
/// `Camera{}`: FBX camera definition
Camera(usize),
/// `Texture{}`: FBX texture reference
Texture(usize),
/// `DefaultScene`: Main scene with all objects
DefaultScene,
/// `DefaultMaterial`: Fallback material used when no material is present
DefaultMaterial,
/// `RootNode`: Root node of the scene hierarchy
RootNode,
}
impl core::fmt::Display for FbxAssetLabel {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FbxAssetLabel::Scene(index) => f.write_str(&format!("Scene{index}")),
FbxAssetLabel::Mesh(index) => f.write_str(&format!("Mesh{index}")),
FbxAssetLabel::Material(index) => f.write_str(&format!("Material{index}")),
FbxAssetLabel::Animation(index) => f.write_str(&format!("Animation{index}")),
FbxAssetLabel::AnimationStack(index) => f.write_str(&format!("AnimationStack{index}")),
FbxAssetLabel::Skeleton(index) => f.write_str(&format!("Skeleton{index}")),
FbxAssetLabel::Node(index) => f.write_str(&format!("Node{index}")),
FbxAssetLabel::Skin(index) => f.write_str(&format!("Skin{index}")),
FbxAssetLabel::Light(index) => f.write_str(&format!("Light{index}")),
FbxAssetLabel::Camera(index) => f.write_str(&format!("Camera{index}")),
FbxAssetLabel::Texture(index) => f.write_str(&format!("Texture{index}")),
FbxAssetLabel::DefaultScene => f.write_str("DefaultScene"),
FbxAssetLabel::DefaultMaterial => f.write_str("DefaultMaterial"),
FbxAssetLabel::RootNode => f.write_str("RootNode"),
}
}
}
impl FbxAssetLabel {
/// Add this label to an asset path
pub fn from_asset(&self, path: impl Into<AssetPath<'static>>) -> AssetPath<'static> {
path.into().with_label(self.to_string())
}
}
+53
View File
@@ -0,0 +1,53 @@
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![forbid(unsafe_code)]
#![doc(
html_logo_url = "https://bevyengine.org/assets/icon.png",
html_favicon_url = "https://bevyengine.org/assets/icon.png"
)]
//! Loader for FBX scenes using [`ufbx`](https://github.com/ufbx/ufbx-rust).
//!
//! This plugin provides comprehensive FBX file loading support for Bevy, including:
//! - Mesh geometry with multi-material support
//! - PBR materials with textures
//! - Skeletal animation and skinning
//! - Scene hierarchy with nodes
//! - Lights and cameras
//! - Animation clips with curves
use bevy::asset::AssetApp;
use bevy::prelude::*;
pub mod error;
pub mod label;
pub mod loader;
pub mod material;
pub mod mesh;
pub mod node;
pub mod scene;
pub mod types;
pub mod utils;
pub use error::FbxError;
pub use label::FbxAssetLabel;
pub use loader::{FbxLoader, FbxLoaderSettings};
pub use types::*;
pub mod prelude {
//! Commonly used items.
pub use crate::{Fbx, FbxAssetLabel, FbxLoaderSettings, FbxNode, FbxPlugin, FbxSkin, Skeleton};
}
/// Plugin adding the FBX loader to an [`App`].
#[derive(Default)]
pub struct FbxPlugin;
impl Plugin for FbxPlugin {
fn build(&self, app: &mut App) {
app.init_asset::<Fbx>()
.init_asset::<FbxNode>()
.init_asset::<FbxSkin>()
.init_asset::<Skeleton>()
.register_asset_loader(FbxLoader::default());
}
}
+150
View File
@@ -0,0 +1,150 @@
//! FBX loader implementation for Bevy.
use crate::error::FbxError;
use crate::material::process_materials;
use crate::mesh::process_meshes;
use crate::node::{process_nodes, process_skins};
use crate::scene::build_scene;
use crate::types::{Fbx, FbxAxisSystem, FbxMeta, Handedness};
use bevy::asset::{io::Reader, AssetLoader, LoadContext, RenderAssetUsages};
use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Settings for FBX file loading.
///
/// These settings allow customizing which parts of the FBX file are loaded
/// and how they are processed.
#[derive(Serialize, Deserialize)]
pub struct FbxLoaderSettings {
/// How meshes should be loaded and used
pub load_meshes: RenderAssetUsages,
/// How materials should be loaded and used
pub load_materials: RenderAssetUsages,
/// Whether to load cameras from the FBX file
pub load_cameras: bool,
/// Whether to load lights from the FBX file
pub load_lights: bool,
/// Whether to include raw source data in the loaded asset
pub include_source: bool,
/// Whether to convert coordinate systems (e.g., Y-up to Z-up)
pub convert_coordinates: bool,
}
impl Default for FbxLoaderSettings {
fn default() -> Self {
Self {
load_meshes: RenderAssetUsages::default(),
load_materials: RenderAssetUsages::default(),
load_cameras: true,
load_lights: true,
include_source: false,
convert_coordinates: false,
}
}
}
/// Loader implementation for FBX files.
///
/// This loader handles reading FBX files and converting them into Bevy assets,
/// including meshes, materials, animations, and scene hierarchies.
#[derive(Default, bevy::reflect::TypePath)]
pub struct FbxLoader;
impl AssetLoader for FbxLoader {
type Asset = Fbx;
type Settings = FbxLoaderSettings;
type Error = FbxError;
async fn load(
&self,
reader: &mut dyn Reader,
settings: &Self::Settings,
load_context: &mut LoadContext<'_>,
) -> Result<Fbx, FbxError> {
// Read file
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
// Basic validation
if bytes.is_empty() {
return Err(FbxError::InvalidData("Empty FBX file".to_string()));
}
if bytes.len() < 32 {
return Err(FbxError::InvalidData("FBX file too small".to_string()));
}
// Parse with ufbx
// Provide the asset path as a filename hint so ufbx can compute relative_filename
let filename_hint = load_context.path().path().to_string_lossy().to_string();
let root = ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
filename: ufbx::StringOpt::Ref(&filename_hint),
..Default::default()
},
)
.map_err(|e| FbxError::UfbxError(format!("{:?}", e)))?;
let scene: &ufbx::Scene = &*root;
// Process meshes
let (meshes, named_meshes, mesh_transforms, mesh_material_info) =
process_meshes(scene, settings, load_context)?;
// Process materials and textures
let (materials, named_materials) = if !settings.load_materials.is_empty() {
process_materials(scene, settings, load_context)?
} else {
(Vec::new(), HashMap::new())
};
// Process nodes and hierarchy
let (nodes, named_nodes, node_map) = process_nodes(scene, &meshes, load_context)?;
// Process skins
let (skins, named_skins) = process_skins(scene, &node_map, load_context)?;
// Build scene
let scene_handle = build_scene(
scene,
&meshes,
&materials,
&named_materials,
&mesh_transforms,
&mesh_material_info,
settings,
load_context,
)?;
// Extract metadata
let metadata = FbxMeta::default();
// Build final FBX asset
Ok(Fbx {
scenes: vec![scene_handle.clone()],
named_scenes: HashMap::new(),
meshes,
named_meshes,
materials,
named_materials,
nodes,
named_nodes,
skins,
named_skins,
default_scene: Some(scene_handle),
axis_system: FbxAxisSystem {
up: Vec3::Y,
front: Vec3::Z,
handedness: Handedness::Right,
},
unit_scale: 1.0,
metadata,
})
}
fn extensions(&self) -> &[&str] {
&["fbx"]
}
}
+246
View File
@@ -0,0 +1,246 @@
//! Material and texture processing for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::loader::FbxLoaderSettings;
use crate::utils::convert_texture_uv_transform;
use bevy::asset::{Handle, LoadContext};
use bevy::pbr::StandardMaterial;
use bevy::prelude::*;
use bevy_material::AlphaMode;
use bevy_image::{CompressedImageFormats, ImageSampler, ImageType};
use std::collections::HashMap;
/// Process all materials from the FBX scene.
pub fn process_materials(
scene: &ufbx::Scene,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<
(
Vec<Handle<StandardMaterial>>,
HashMap<Box<str>, Handle<StandardMaterial>>,
),
FbxError,
> {
let mut materials = Vec::new();
let mut named_materials = HashMap::new();
let texture_handles = process_textures(scene, settings, load_context)?;
for (index, ufbx_material) in scene.materials.as_ref().iter().enumerate() {
if ufbx_material.element.element_id == 0 {
continue;
}
let standard_material = create_standard_material(ufbx_material, &texture_handles)?;
let handle = load_context.add_labeled_asset(
FbxAssetLabel::Material(index).to_string(),
standard_material,
);
if !ufbx_material.element.name.is_empty() {
named_materials.insert(
Box::from(ufbx_material.element.name.as_ref()),
handle.clone(),
);
}
materials.push(handle);
}
Ok((materials, named_materials))
}
/// Process textures from materials.
///
/// Uses the following priority for each texture:
/// 1. Embedded textures (`texture.content` non-empty) — decoded via `Image::from_buffer`
/// 2. External textures via `texture.relative_filename` — already relative to the FBX file
/// 3. External textures via `.fbm` folder extraction from `texture.filename` / `texture.absolute_filename`
pub fn process_textures(
scene: &ufbx::Scene,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<HashMap<u32, Handle<Image>>, FbxError> {
let mut texture_handles = HashMap::new();
for (index, texture) in scene.textures.as_ref().iter().enumerate() {
let asset_path = load_context.path().clone();
let fbx_dir = asset_path
.path()
.parent()
.unwrap_or_else(|| std::path::Path::new(""))
.to_path_buf();
// Priority 1: Embedded texture data
if !texture.content.is_empty() {
let ext = extract_extension(&texture.filename).unwrap_or("png");
match Image::from_buffer(
&texture.content,
ImageType::Extension(ext),
CompressedImageFormats::NONE,
true, // is_srgb
ImageSampler::Default,
settings.load_materials,
) {
Ok(image) => {
let handle = load_context.add_labeled_asset(
FbxAssetLabel::Texture(index).to_string(),
image,
);
texture_handles.insert(texture.element.element_id, handle);
continue;
}
Err(e) => {
eprintln!("bevy_ufbx: failed to load embedded texture {index}: {e}");
// Fall through to try external paths
}
}
}
// Priority 2: relative_filename from ufbx (relative to FBX file)
if !texture.relative_filename.is_empty() {
let rel = texture.relative_filename.as_ref();
let is_absolute = rel.starts_with('/')
|| (rel.len() >= 3 && rel.chars().nth(1) == Some(':'));
if !is_absolute {
let texture_path = fbx_dir.join(rel).to_string_lossy().to_string();
let image_handle = load_context.load(texture_path);
texture_handles.insert(texture.element.element_id, image_handle);
continue;
}
}
// Priority 3: Extract relative path from filename / absolute_filename
// Preserves .fbm folder structure if present (e.g., "model.fbm/texture.jpg")
let relative_path = extract_relative_texture_path(texture);
if !relative_path.is_empty() {
let texture_path = fbx_dir
.join(relative_path)
.to_string_lossy()
.to_string();
let image_handle = load_context.load(texture_path);
texture_handles.insert(texture.element.element_id, image_handle);
}
}
Ok(texture_handles)
}
/// Extract file extension from a texture filename string.
fn extract_extension(filename: &ufbx::String) -> Option<&str> {
if filename.is_empty() {
return None;
}
let s = filename.as_ref();
s.rsplit('.')
.next()
.filter(|ext| !ext.contains('/') && !ext.contains('\\'))
}
/// Extract a relative texture path from a ufbx Texture's filename or absolute_filename.
///
/// Handles absolute paths by looking for `.fbm` folders (FBX's standard embedded texture
/// directory) and extracting from there, or falling back to just the filename.
fn extract_relative_texture_path<'a>(texture: &'a ufbx::Texture) -> &'a str {
if !texture.filename.is_empty() {
let filename = texture.filename.as_ref();
let is_absolute = filename.starts_with('/')
|| (filename.len() >= 3 && filename.chars().nth(1) == Some(':'));
if is_absolute {
extract_from_absolute(filename)
} else {
filename
}
} else if !texture.absolute_filename.is_empty() {
extract_from_absolute(texture.absolute_filename.as_ref())
} else {
""
}
}
/// Extract a relative path from an absolute path, preserving `.fbm` folder structure.
fn extract_from_absolute(path: &str) -> &str {
if let Some(fbm_pos) = path.rfind(".fbm/").or_else(|| path.rfind(".fbm\\")) {
let before_fbm = &path[..fbm_pos];
let folder_start = before_fbm
.rfind(&['/', '\\'][..])
.map(|p| p + 1)
.unwrap_or(0);
&path[folder_start..]
} else {
let last_slash = path.rfind(&['/', '\\'][..]);
if let Some(pos) = last_slash {
&path[pos + 1..]
} else {
path
}
}
}
/// Create a StandardMaterial from ufbx material.
pub fn create_standard_material(
ufbx_material: &ufbx::Material,
texture_handles: &HashMap<u32, Handle<Image>>,
) -> Result<StandardMaterial, FbxError> {
let mut material = StandardMaterial::default();
// Base color
if let Ok(diffuse) = std::panic::catch_unwind(|| ufbx_material.fbx.diffuse_color.value_vec4) {
material.base_color = Color::srgb(diffuse.x as f32, diffuse.y as f32, diffuse.z as f32);
} else if let Ok(pbr_base) =
std::panic::catch_unwind(|| ufbx_material.pbr.base_color.value_vec4)
{
material.base_color = Color::srgb(pbr_base.x as f32, pbr_base.y as f32, pbr_base.z as f32);
}
// Metallic and roughness
if let Ok(metallic) = std::panic::catch_unwind(|| ufbx_material.pbr.metalness.value_vec4) {
material.metallic = metallic.x as f32;
}
if let Ok(roughness) = std::panic::catch_unwind(|| ufbx_material.pbr.roughness.value_vec4) {
material.perceptual_roughness = roughness.x as f32;
}
// Emission
if let Ok(emission) = std::panic::catch_unwind(|| ufbx_material.fbx.emission_color.value_vec4) {
material.emissive =
LinearRgba::rgb(emission.x as f32, emission.y as f32, emission.z as f32);
}
// Alpha
if ufbx_material.pbr.opacity.value_vec4.x < 1.0 {
let alpha = ufbx_material.pbr.opacity.value_vec4.x as f32;
material.alpha_mode = if alpha < 0.98 {
AlphaMode::Blend
} else {
AlphaMode::Opaque
};
}
// Textures
for texture_ref in &ufbx_material.textures {
if let Some(image_handle) = texture_handles.get(&texture_ref.texture.element.element_id) {
match texture_ref.material_prop.as_ref() {
"DiffuseColor" | "BaseColor" => {
material.base_color_texture = Some(image_handle.clone());
material.uv_transform = convert_texture_uv_transform(&texture_ref.texture);
}
"NormalMap" => material.normal_map_texture = Some(image_handle.clone()),
"Metallic" => material.metallic_roughness_texture = Some(image_handle.clone()),
"Roughness" if material.metallic_roughness_texture.is_none() => {
material.metallic_roughness_texture = Some(image_handle.clone());
}
"EmissiveColor" => material.emissive_texture = Some(image_handle.clone()),
"AmbientOcclusion" => material.occlusion_texture = Some(image_handle.clone()),
_ => {}
}
}
}
Ok(material)
}
+218
View File
@@ -0,0 +1,218 @@
//! Mesh processing functionality for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::loader::FbxLoaderSettings;
use bevy::asset::{Handle, LoadContext};
use bevy::prelude::*;
use bevy::mesh::{Indices, PrimitiveTopology, VertexAttributeValues};
use std::collections::HashMap;
/// Process all meshes from the FBX scene.
pub fn process_meshes(
scene: &ufbx::Scene,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<
(
Vec<Handle<Mesh>>,
HashMap<Box<str>, Handle<Mesh>>,
Vec<ufbx::Matrix>,
Vec<Vec<String>>,
),
FbxError,
> {
let mut meshes = Vec::new();
let mut named_meshes = HashMap::new();
let mut transforms = Vec::new();
let mut mesh_material_info = Vec::new();
for (index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = node.mesh.as_ref() else {
continue;
};
let mesh = mesh_ref.as_ref();
if mesh.num_vertices == 0 || mesh.faces.as_ref().is_empty() {
continue;
}
// Group faces by material
let material_groups = group_faces_by_material(mesh);
// Create mesh for each material group
for (material_idx, indices) in material_groups.iter() {
let mesh_handle = create_mesh_from_group(
mesh,
indices,
index,
*material_idx,
settings,
load_context,
)?;
if *material_idx == 0 && !node.element.name.is_empty() {
named_meshes.insert(Box::from(node.element.name.as_ref()), mesh_handle.clone());
}
meshes.push(mesh_handle);
transforms.push(node.geometry_to_world);
let material_name = if *material_idx < mesh.materials.len() {
mesh.materials[*material_idx].element.name.to_string()
} else {
"default".to_string()
};
mesh_material_info.push(vec![material_name]);
}
}
Ok((meshes, named_meshes, transforms, mesh_material_info))
}
/// Group mesh faces by material index.
pub fn group_faces_by_material(mesh: &ufbx::Mesh) -> HashMap<usize, Vec<u32>> {
let mut material_groups: HashMap<usize, Vec<u32>> = HashMap::new();
let mut scratch = Vec::new();
if mesh.materials.is_empty() {
// No materials - create single group
let mut all_indices = Vec::new();
for &face in mesh.faces.as_ref().iter() {
scratch.clear();
ufbx::triangulate_face_vec(&mut scratch, mesh, face);
for idx in &scratch {
if (*idx as usize) < mesh.vertex_indices.len() {
all_indices.push(mesh.vertex_indices[*idx as usize]);
}
}
}
material_groups.insert(0, all_indices);
} else {
// Group by material
for (face_idx, &face) in mesh.faces.as_ref().iter().enumerate() {
let material_idx =
if !mesh.face_material.is_empty() && face_idx < mesh.face_material.len() {
mesh.face_material[face_idx] as usize
} else {
0
};
scratch.clear();
ufbx::triangulate_face_vec(&mut scratch, mesh, face);
let indices = material_groups.entry(material_idx).or_insert_with(Vec::new);
for idx in &scratch {
if (*idx as usize) < mesh.vertex_indices.len() {
indices.push(mesh.vertex_indices[*idx as usize]);
}
}
}
}
material_groups
}
/// Create a Bevy mesh from a material group.
pub fn create_mesh_from_group(
ufbx_mesh: &ufbx::Mesh,
indices: &[u32],
mesh_index: usize,
material_index: usize,
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<Handle<Mesh>, FbxError> {
let label = FbxAssetLabel::Mesh(mesh_index * 1000 + material_index).to_string();
let handle = load_context.labeled_asset_scope(label, |_| {
let mut bevy_mesh = Mesh::new(PrimitiveTopology::TriangleList, settings.load_meshes);
// Positions
let positions: Vec<[f32; 3]> = ufbx_mesh
.vertex_position
.values
.as_ref()
.iter()
.map(|v| [v.x as f32, v.y as f32, v.z as f32])
.collect();
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, positions);
// Normals
if ufbx_mesh.vertex_normal.exists {
let normals: Vec<[f32; 3]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let n = ufbx_mesh.vertex_normal[i];
[n.x as f32, n.y as f32, n.z as f32]
})
.collect();
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, normals);
}
// UVs
if ufbx_mesh.vertex_uv.exists {
let uvs: Vec<[f32; 2]> = (0..ufbx_mesh.num_vertices)
.map(|i| {
let uv = ufbx_mesh.vertex_uv[i];
[uv.x as f32, uv.y as f32]
})
.collect();
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, uvs);
}
// Skinning
if !ufbx_mesh.skin_deformers.is_empty() {
process_skinning_data(ufbx_mesh, &mut bevy_mesh);
}
// Indices
bevy_mesh.insert_indices(Indices::U32(indices.to_vec()));
Ok::<_, FbxError>(bevy_mesh)
})?;
Ok(handle)
}
/// Process skinning data for a mesh.
pub fn process_skinning_data(ufbx_mesh: &ufbx::Mesh, bevy_mesh: &mut Mesh) {
let skin_deformer = &ufbx_mesh.skin_deformers[0];
let mut joint_indices = vec![[0u16; 4]; ufbx_mesh.num_vertices];
let mut joint_weights = vec![[0.0f32; 4]; ufbx_mesh.num_vertices];
for vertex_index in 0..ufbx_mesh.num_vertices {
let mut weight_count = 0;
let mut total_weight = 0.0f32;
for (cluster_index, cluster) in skin_deformer.clusters.iter().enumerate() {
if weight_count >= 4 {
break;
}
for (i, &vert_idx) in cluster.vertices.iter().enumerate() {
if vert_idx as usize == vertex_index && i < cluster.weights.len() {
let weight = cluster.weights[i] as f32;
if weight > 0.0 {
joint_indices[vertex_index][weight_count] = cluster_index as u16;
joint_weights[vertex_index][weight_count] = weight;
total_weight += weight;
weight_count += 1;
break;
}
}
}
}
// Normalize weights
if total_weight > 0.0 {
for i in 0..weight_count {
joint_weights[vertex_index][i] /= total_weight;
}
}
}
bevy_mesh.insert_attribute(
Mesh::ATTRIBUTE_JOINT_INDEX,
VertexAttributeValues::Uint16x4(joint_indices),
);
bevy_mesh.insert_attribute(Mesh::ATTRIBUTE_JOINT_WEIGHT, joint_weights);
}
+135
View File
@@ -0,0 +1,135 @@
//! Node and hierarchy processing for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::types::{FbxNode, FbxSkin};
use crate::utils::{convert_matrix, convert_transform};
use bevy::asset::{Handle, LoadContext};
use bevy::prelude::*;
use bevy::mesh::skinning::SkinnedMeshInverseBindposes;
use std::collections::HashMap;
/// Process nodes and build hierarchy.
pub fn process_nodes(
scene: &ufbx::Scene,
meshes: &[Handle<Mesh>],
load_context: &mut LoadContext,
) -> Result<
(
Vec<Handle<FbxNode>>,
HashMap<Box<str>, Handle<FbxNode>>,
HashMap<u32, Handle<FbxNode>>,
),
FbxError,
> {
let mut nodes = Vec::new();
let mut named_nodes = HashMap::new();
let mut node_map = HashMap::new();
// First pass: create nodes
for (index, ufbx_node) in scene.nodes.as_ref().iter().enumerate() {
let name = if ufbx_node.element.name.is_empty() {
format!("Node_{}", index)
} else {
ufbx_node.element.name.to_string()
};
let mesh_handle = if ufbx_node.mesh.is_some() && index < meshes.len() {
Some(meshes[index].clone())
} else {
None
};
let fbx_node = FbxNode {
index,
name: name.clone(),
children: Vec::new(),
mesh: mesh_handle,
skin: None,
transform: convert_transform(&ufbx_node.local_transform),
visible: ufbx_node.visible,
};
let handle =
load_context.add_labeled_asset(FbxAssetLabel::Node(index).to_string(), fbx_node);
node_map.insert(ufbx_node.element.element_id, handle.clone());
nodes.push(handle.clone());
if !ufbx_node.element.name.is_empty() {
named_nodes.insert(Box::from(ufbx_node.element.name.as_ref()), handle);
}
}
// Note: Hierarchy building would require mutable access to nodes
// which is not possible with the current asset system.
// Parent-child relationships would need to be established at runtime.
Ok((nodes, named_nodes, node_map))
}
/// Process skins for skeletal animation.
pub fn process_skins(
scene: &ufbx::Scene,
node_map: &HashMap<u32, Handle<FbxNode>>,
load_context: &mut LoadContext,
) -> Result<(Vec<Handle<FbxSkin>>, HashMap<Box<str>, Handle<FbxSkin>>), FbxError> {
let mut skins = Vec::new();
let mut named_skins = HashMap::new();
for (skin_index, node) in scene.nodes.as_ref().iter().enumerate() {
let Some(mesh_ref) = &node.mesh else {
continue;
};
let mesh = mesh_ref.as_ref();
if mesh.skin_deformers.is_empty() {
continue;
}
let skin_deformer = &mesh.skin_deformers[0];
let mut inverse_bind_matrices = Vec::new();
let mut joint_handles = Vec::new();
for cluster in &skin_deformer.clusters {
let bind_matrix = convert_matrix(&cluster.bind_to_world);
inverse_bind_matrices.push(bind_matrix.inverse());
if let Some(bone_node) = cluster.bone_node.as_ref() {
if let Some(joint_handle) = node_map.get(&bone_node.element.element_id) {
joint_handles.push(joint_handle.clone());
}
}
}
if !inverse_bind_matrices.is_empty() {
let inverse_bindposes_handle = load_context.add_labeled_asset(
format!("Skin_{}_InverseBindposes", skin_index),
SkinnedMeshInverseBindposes::from(inverse_bind_matrices),
);
let skin_name = if node.element.name.is_empty() {
format!("Skin_{}", skin_index)
} else {
format!("{}_Skin", node.element.name)
};
let fbx_skin = FbxSkin {
index: skin_index,
name: skin_name.clone(),
joints: joint_handles,
inverse_bind_matrices: inverse_bindposes_handle,
};
let handle = load_context
.add_labeled_asset(FbxAssetLabel::Skin(skin_index).to_string(), fbx_skin);
skins.push(handle.clone());
if !skin_name.starts_with("Skin_") {
named_skins.insert(Box::from(skin_name.as_str()), handle);
}
}
}
Ok((skins, named_skins))
}
+142
View File
@@ -0,0 +1,142 @@
//! Scene building functionality for FBX files.
use crate::error::FbxError;
use crate::label::FbxAssetLabel;
use crate::loader::FbxLoaderSettings;
use crate::utils::convert_matrix;
use bevy::asset::{Handle, LoadContext};
use bevy::pbr::StandardMaterial;
use bevy::prelude::*;
use bevy::world_serialization::WorldAsset;
use std::collections::HashMap;
/// Build the final scene with all entities.
pub fn build_scene(
scene: &ufbx::Scene,
meshes: &[Handle<Mesh>],
materials: &[Handle<StandardMaterial>],
named_materials: &HashMap<Box<str>, Handle<StandardMaterial>>,
mesh_transforms: &[ufbx::Matrix],
mesh_material_info: &[Vec<String>],
settings: &FbxLoaderSettings,
load_context: &mut LoadContext,
) -> Result<Handle<WorldAsset>, FbxError> {
let mut world = World::new();
// Create default material if needed
let default_material = materials.get(0).cloned().unwrap_or_else(|| {
load_context.add_labeled_asset(
FbxAssetLabel::DefaultMaterial.to_string(),
StandardMaterial::default(),
)
});
// Spawn meshes
for (mesh_index, ((mesh_handle, transform_matrix), mat_names)) in meshes
.iter()
.zip(mesh_transforms.iter())
.zip(mesh_material_info.iter())
.enumerate()
{
let transform = Transform::from_matrix(convert_matrix(transform_matrix));
// Find material
let material = mat_names
.iter()
.find_map(|name| named_materials.get(name as &str))
.cloned()
.or_else(|| {
materials
.get(mesh_index.min(materials.len().saturating_sub(1)))
.cloned()
})
.unwrap_or_else(|| default_material.clone());
world.spawn((
Mesh3d(mesh_handle.clone()),
MeshMaterial3d(material),
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
// Spawn lights
if settings.load_lights {
spawn_lights(scene, &mut world);
}
let scene_handle =
load_context.add_labeled_asset(FbxAssetLabel::Scene(0).to_string(), WorldAsset::new(world));
Ok(scene_handle)
}
/// Spawn lights in the scene.
pub fn spawn_lights(scene: &ufbx::Scene, world: &mut World) {
for light in scene.lights.as_ref().iter() {
if let Some(light_node) = scene.nodes.as_ref().iter().find(|n| {
n.light.is_some()
&& n.light.as_ref().unwrap().element.element_id == light.element.element_id
}) {
let transform = Transform::from_matrix(convert_matrix(&light_node.node_to_world));
match light.type_ {
ufbx::LightType::Directional => {
world.spawn((
DirectionalLight {
color: Color::srgb(
light.color.x as f32,
light.color.y as f32,
light.color.z as f32,
),
illuminance: light.intensity as f32 * 10000.0,
shadow_maps_enabled: light.cast_shadows,
..Default::default()
},
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
ufbx::LightType::Point => {
world.spawn((
PointLight {
color: Color::srgb(
light.color.x as f32,
light.color.y as f32,
light.color.z as f32,
),
intensity: light.intensity as f32 * 1000.0,
shadow_maps_enabled: light.cast_shadows,
..Default::default()
},
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
ufbx::LightType::Spot => {
world.spawn((
SpotLight {
color: Color::srgb(
light.color.x as f32,
light.color.y as f32,
light.color.z as f32,
),
intensity: light.intensity as f32 * 1000.0,
shadow_maps_enabled: light.cast_shadows,
inner_angle: light.inner_angle as f32,
outer_angle: light.outer_angle as f32,
..Default::default()
},
transform,
GlobalTransform::default(),
Visibility::default(),
));
}
_ => {}
}
}
}
}
+195
View File
@@ -0,0 +1,195 @@
//! Type definitions for the FBX loader.
use bevy::asset::{Asset, Handle};
use bevy::math::Affine2;
use bevy::pbr::StandardMaterial;
use bevy::prelude::*;
use bevy::mesh::skinning::SkinnedMeshInverseBindposes;
use bevy::world_serialization::WorldAsset;
use std::collections::HashMap;
// ============================================================================
// Coordinate System
// ============================================================================
/// Handedness of a coordinate system.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Handedness {
Right,
Left,
}
/// Coordinate axes definition.
#[derive(Debug, Clone, Copy)]
pub struct FbxAxisSystem {
pub up: Vec3,
pub front: Vec3,
pub handedness: Handedness,
}
// ============================================================================
// Metadata
// ============================================================================
/// Metadata from FBX header.
#[derive(Debug, Clone, Default)]
pub struct FbxMeta {
pub creator: Option<String>,
pub creation_time: Option<String>,
pub original_application: Option<String>,
}
// ============================================================================
// Textures and Materials
// ============================================================================
/// Texture wrapping modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxWrapMode {
Repeat,
Clamp,
}
/// Types of textures in FBX materials.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FbxTextureType {
BaseColor,
Normal,
Metallic,
Roughness,
Emission,
AmbientOcclusion,
Height,
}
/// Texture information.
#[derive(Debug, Clone)]
pub struct FbxTexture {
pub name: String,
pub filename: String,
pub absolute_filename: String,
pub uv_set: String,
pub uv_transform: Affine2,
pub wrap_u: FbxWrapMode,
pub wrap_v: FbxWrapMode,
}
/// Material representation.
#[derive(Debug, Clone)]
pub struct FbxMaterial {
pub name: String,
pub base_color: Color,
pub metallic: f32,
pub roughness: f32,
pub emission: Color,
pub normal_scale: f32,
pub alpha: f32,
pub alpha_cutoff: f32,
pub double_sided: bool,
pub textures: HashMap<FbxTextureType, FbxTexture>,
}
// ============================================================================
// Lights and Cameras
// ============================================================================
/// Light types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxLightType {
Directional,
Point,
Spot,
Area,
Volume,
}
/// Light definition.
#[derive(Debug, Clone)]
pub struct FbxLight {
pub name: String,
pub light_type: FbxLightType,
pub color: Color,
pub intensity: f32,
pub cast_shadows: bool,
pub inner_angle: Option<f32>,
pub outer_angle: Option<f32>,
}
/// Camera projection modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxProjectionMode {
Perspective,
Orthographic,
}
/// Camera definition.
#[derive(Debug, Clone)]
pub struct FbxCamera {
pub name: String,
pub projection_mode: FbxProjectionMode,
pub field_of_view_deg: f32,
pub aspect_ratio: f32,
pub near_plane: f32,
pub far_plane: f32,
pub focal_length_mm: f32,
}
// ============================================================================
// Scene Elements
// ============================================================================
/// FBX node with hierarchy.
#[derive(Asset, Debug, Clone, TypePath)]
pub struct FbxNode {
pub index: usize,
pub name: String,
pub children: Vec<Handle<FbxNode>>,
pub mesh: Option<Handle<Mesh>>,
pub skin: Option<Handle<FbxSkin>>,
pub transform: Transform,
pub visible: bool,
}
/// FBX skin for skeletal animation.
#[derive(Asset, Debug, Clone, TypePath)]
pub struct FbxSkin {
pub index: usize,
pub name: String,
pub joints: Vec<Handle<FbxNode>>,
pub inverse_bind_matrices: Handle<SkinnedMeshInverseBindposes>,
}
/// Placeholder for skeleton data.
#[derive(Asset, Debug, Clone, TypePath)]
pub struct Skeleton;
/// Animation interpolation modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxInterpolation {
Constant,
Linear,
Cubic,
}
// ============================================================================
// Main FBX Asset
// ============================================================================
/// Representation of a loaded FBX file.
#[derive(Asset, Debug, TypePath)]
pub struct Fbx {
pub scenes: Vec<Handle<WorldAsset>>,
pub named_scenes: HashMap<Box<str>, Handle<WorldAsset>>,
pub meshes: Vec<Handle<Mesh>>,
pub named_meshes: HashMap<Box<str>, Handle<Mesh>>,
pub materials: Vec<Handle<StandardMaterial>>,
pub named_materials: HashMap<Box<str>, Handle<StandardMaterial>>,
pub nodes: Vec<Handle<FbxNode>>,
pub named_nodes: HashMap<Box<str>, Handle<FbxNode>>,
pub skins: Vec<Handle<FbxSkin>>,
pub named_skins: HashMap<Box<str>, Handle<FbxSkin>>,
pub default_scene: Option<Handle<WorldAsset>>,
pub axis_system: FbxAxisSystem,
pub unit_scale: f32,
pub metadata: FbxMeta,
}
+58
View File
@@ -0,0 +1,58 @@
//! Utility functions for converting between ufbx and Bevy types.
use bevy::math::{Affine2, Mat4};
use bevy::prelude::*;
/// Convert ufbx texture UV transform to Bevy Affine2.
pub fn convert_texture_uv_transform(texture: &ufbx::Texture) -> Affine2 {
let translation = Vec2::new(
texture.uv_transform.translation.x as f32,
texture.uv_transform.translation.y as f32,
);
let scale = Vec2::new(
texture.uv_transform.scale.x as f32,
texture.uv_transform.scale.y as f32,
);
let rotation_z = texture.uv_transform.rotation.z as f32;
Affine2::from_scale_angle_translation(scale, rotation_z, translation)
}
/// Convert ufbx matrix to Bevy Mat4.
pub fn convert_matrix(m: &ufbx::Matrix) -> Mat4 {
Mat4::from_cols_array(&[
m.m00 as f32,
m.m10 as f32,
m.m20 as f32,
0.0,
m.m01 as f32,
m.m11 as f32,
m.m21 as f32,
0.0,
m.m02 as f32,
m.m12 as f32,
m.m22 as f32,
0.0,
m.m03 as f32,
m.m13 as f32,
m.m23 as f32,
1.0,
])
}
/// Convert ufbx transform to Bevy Transform.
pub fn convert_transform(t: &ufbx::Transform) -> Transform {
Transform {
translation: Vec3::new(
t.translation.x as f32,
t.translation.y as f32,
t.translation.z as f32,
),
rotation: Quat::from_xyzw(
t.rotation.x as f32,
t.rotation.y as f32,
t.rotation.z as f32,
t.rotation.w as f32,
),
scale: Vec3::new(t.scale.x as f32, t.scale.y as f32, t.scale.z as f32),
}
}
+25
View File
@@ -0,0 +1,25 @@
use bevy::prelude::*;
use bevy_ufbx::FbxPlugin;
#[test]
fn test_plugin_builds() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
app.add_plugins(FbxPlugin);
// If we get here without panic, the plugin is properly set up
assert!(true);
}
#[test]
fn test_loader_registration() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
app.add_plugins(FbxPlugin);
// Check that FBX extensions are registered
// This is a basic test that the loader is registered
assert!(true);
}
+99
View File
@@ -0,0 +1,99 @@
//! Integration tests for FBX loading.
use bevy::asset::{AssetPlugin, AssetServer};
use bevy::prelude::*;
use bevy_ufbx::{Fbx, FbxPlugin};
#[test]
fn test_plugin_initialization() {
let mut app = App::new();
// Add required plugins
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
app.add_plugins(FbxPlugin);
// Check that the plugin initialized correctly
app.update();
// If we get here without panic, the plugin is working
assert!(true);
}
#[test]
fn test_asset_registration() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
app.add_plugins(FbxPlugin);
// Check that Fbx asset is registered
let asset_server = app.world().resource::<AssetServer>();
// This would typically be tested by loading an actual FBX file
// For now, we just verify the asset server exists
assert!(
asset_server.mode() == bevy::asset::AssetServerMode::Processed
|| asset_server.mode() == bevy::asset::AssetServerMode::Unprocessed
);
}
// Test system to verify FBX loading
fn check_fbx_loaded(
_asset_server: Res<AssetServer>,
fbx_assets: Res<Assets<Fbx>>,
mut loaded: Local<bool>,
) {
if *loaded {
return;
}
// In a real test, we would load an actual FBX file
// For now, we just verify the system can access the resources
let _ = fbx_assets.len();
*loaded = true;
}
#[test]
fn test_fbx_loading_system() {
let mut app = App::new();
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
app.add_plugins(FbxPlugin);
app.add_systems(Update, check_fbx_loaded);
// Run a few update cycles
for _ in 0..3 {
app.update();
}
// If we get here without panic, systems are working
assert!(true);
}
#[test]
fn test_multiple_plugins() {
let mut app = App::new();
// Test that we can add multiple instances of required plugins
app.add_plugins(MinimalPlugins);
app.add_plugins(AssetPlugin::default());
app.add_plugins(FbxPlugin);
// Add some standard Bevy plugins that might interact with FBX loading
app.init_resource::<Assets<Mesh>>();
app.init_resource::<Assets<StandardMaterial>>();
app.update();
// Verify resources exist
assert!(app.world().get_resource::<Assets<Mesh>>().is_some());
assert!(app
.world()
.get_resource::<Assets<StandardMaterial>>()
.is_some());
assert!(app.world().get_resource::<Assets<Fbx>>().is_some());
}
+78
View File
@@ -0,0 +1,78 @@
//! Tests for FBX asset labels.
use bevy_ufbx::FbxAssetLabel;
#[test]
fn test_scene_label() {
let label = FbxAssetLabel::Scene(0);
assert_eq!(label.to_string(), "Scene0");
let label = FbxAssetLabel::Scene(42);
assert_eq!(label.to_string(), "Scene42");
}
#[test]
fn test_node_label() {
let label = FbxAssetLabel::Node(5);
assert_eq!(label.to_string(), "Node5");
let label = FbxAssetLabel::Node(999);
assert_eq!(label.to_string(), "Node999");
}
#[test]
fn test_mesh_label() {
let label = FbxAssetLabel::Mesh(10);
assert_eq!(label.to_string(), "Mesh10");
}
#[test]
fn test_material_label() {
let label = FbxAssetLabel::Material(3);
assert_eq!(label.to_string(), "Material3");
}
#[test]
fn test_texture_label() {
let label = FbxAssetLabel::Texture(7);
assert_eq!(label.to_string(), "Texture7");
}
#[test]
fn test_animation_label() {
let label = FbxAssetLabel::Animation(2);
assert_eq!(label.to_string(), "Animation2");
}
#[test]
fn test_skin_label() {
let label = FbxAssetLabel::Skin(4);
assert_eq!(label.to_string(), "Skin4");
}
#[test]
fn test_default_material_label() {
let label = FbxAssetLabel::DefaultMaterial;
assert_eq!(label.to_string(), "DefaultMaterial");
}
#[test]
fn test_label_uniqueness() {
// Test that different label types with same index produce different strings
let scene = FbxAssetLabel::Scene(1);
let node = FbxAssetLabel::Node(1);
let mesh = FbxAssetLabel::Mesh(1);
assert_ne!(scene.to_string(), node.to_string());
assert_ne!(scene.to_string(), mesh.to_string());
assert_ne!(node.to_string(), mesh.to_string());
}
#[test]
fn test_label_consistency() {
// Test that the same label always produces the same string
let label1 = FbxAssetLabel::Material(100);
let label2 = FbxAssetLabel::Material(100);
assert_eq!(label1.to_string(), label2.to_string());
}
+160
View File
@@ -0,0 +1,160 @@
//! Loads every FBX file from the ufbx test suite and verifies our processing
//! functions handle them without panicking or returning unexpected errors.
//!
//! Set the `UFBX_TEST_DATA` environment variable to the path of the
//! `ufbx/data` directory before running:
//!
//! ```sh
//! UFBX_TEST_DATA=/tmp/ufbx/data cargo test load_all_ufbx_test_data -- --nocapture
//! ```
use bevy_ufbx::material::create_standard_material;
use bevy_ufbx::mesh::group_faces_by_material;
use bevy_ufbx::utils::{convert_matrix, convert_transform};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Instant;
/// Subdirectories that contain binary fuzz/garbage data, not valid FBX files.
const SKIP_DIRS: &[&str] = &["fuzz", "cache_fuzz", "obj_fuzz", "mtl_fuzz"];
fn collect_fbx_files(root: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
collect_recursive(root, &mut files);
files.sort();
files
}
fn collect_recursive(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let name = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("");
if !SKIP_DIRS.contains(&name) {
collect_recursive(&path, out);
}
} else if path
.extension()
.and_then(|e| e.to_str())
.map(|e| e.eq_ignore_ascii_case("fbx"))
.unwrap_or(false)
{
out.push(path);
}
}
}
/// Attempt to load an FBX file through the full processing pipeline used by
/// our loader, without needing a `LoadContext`.
///
/// Returns `Ok(())` on success or a human-readable error string.
fn try_process_fbx(path: &Path) -> Result<(), String> {
let bytes = std::fs::read(path).map_err(|e| format!("read: {e}"))?;
let root = ufbx::load_memory(
&bytes,
ufbx::LoadOpts {
target_unit_meters: 1.0,
target_axes: ufbx::CoordinateAxes::right_handed_y_up(),
..Default::default()
},
)
.map_err(|e| format!("ufbx: {e:?}"))?;
let scene: &ufbx::Scene = &*root;
// --- Nodes / transforms ---
for node in scene.nodes.as_ref().iter() {
convert_transform(&node.local_transform);
convert_matrix(&node.node_to_world);
// Mesh face grouping (pure data, no LoadContext needed)
if let Some(mesh_ref) = node.mesh.as_ref() {
let mesh = mesh_ref.as_ref();
if mesh.num_vertices > 0 && !mesh.faces.as_ref().is_empty() {
group_faces_by_material(mesh);
}
}
}
// --- Materials ---
// Pass an empty texture map; we're testing structural correctness, not
// texture path resolution.
let no_textures = HashMap::new();
for mat in scene.materials.as_ref().iter() {
if mat.element.element_id == 0 {
continue;
}
create_standard_material(mat, &no_textures)
.map_err(|e| format!("material '{}': {e:?}", mat.element.name))?;
}
Ok(())
}
#[test]
fn load_all_ufbx_test_data() {
let data_dir = match std::env::var("UFBX_TEST_DATA") {
Ok(dir) => PathBuf::from(dir),
Err(_) => {
println!("Skipping: UFBX_TEST_DATA env var not set.");
println!("To run: UFBX_TEST_DATA=/path/to/ufbx/data cargo test load_all_ufbx_test_data -- --nocapture");
return;
}
};
assert!(
data_dir.is_dir(),
"UFBX_TEST_DATA '{}' is not a directory",
data_dir.display()
);
let fbx_files = collect_fbx_files(&data_dir);
assert!(
!fbx_files.is_empty(),
"No .fbx files found in '{}'",
data_dir.display()
);
println!("Found {} FBX files in {}\n", fbx_files.len(), data_dir.display());
let mut passed = 0usize;
let mut failures: Vec<String> = Vec::new();
let total_start = Instant::now();
for path in &fbx_files {
let rel = path.strip_prefix(&data_dir).unwrap_or(path);
let t = Instant::now();
match try_process_fbx(path) {
Ok(()) => {
passed += 1;
println!(" OK {:>6}ms {}", t.elapsed().as_millis(), rel.display());
}
Err(e) => {
let msg = format!("{} — {}", rel.display(), e);
eprintln!("FAIL {:>6}ms {}", t.elapsed().as_millis(), msg);
failures.push(msg);
}
}
}
let total = fbx_files.len();
println!(
"\n{passed}/{total} passed in {:.2}s",
total_start.elapsed().as_secs_f64()
);
if !failures.is_empty() {
panic!(
"\n{} file(s) failed to process:\n {}",
failures.len(),
failures.join("\n ")
);
}
}
+65
View File
@@ -0,0 +1,65 @@
//! Tests for FBX loader settings.
use bevy::asset::RenderAssetUsages;
use bevy_ufbx::FbxLoaderSettings;
#[test]
fn test_loader_settings_default() {
let settings = FbxLoaderSettings::default();
assert_eq!(settings.load_meshes, RenderAssetUsages::default());
assert_eq!(settings.load_materials, RenderAssetUsages::default());
assert!(settings.load_cameras);
assert!(settings.load_lights);
assert!(!settings.include_source);
assert!(!settings.convert_coordinates);
}
#[test]
fn test_loader_settings_custom() {
let settings = FbxLoaderSettings {
load_meshes: RenderAssetUsages::RENDER_WORLD,
load_materials: RenderAssetUsages::MAIN_WORLD,
load_cameras: false,
load_lights: false,
include_source: true,
convert_coordinates: true,
};
assert_eq!(settings.load_meshes, RenderAssetUsages::RENDER_WORLD);
assert_eq!(settings.load_materials, RenderAssetUsages::MAIN_WORLD);
assert!(!settings.load_cameras);
assert!(!settings.load_lights);
assert!(settings.include_source);
assert!(settings.convert_coordinates);
}
#[test]
fn test_loader_settings_serialization() {
let original = FbxLoaderSettings {
load_meshes: RenderAssetUsages::RENDER_WORLD,
load_materials: RenderAssetUsages::MAIN_WORLD,
load_cameras: false,
load_lights: true,
include_source: false,
convert_coordinates: true,
};
// Serialize
let serialized = serde_json::to_string(&original).expect("Failed to serialize");
// Deserialize
let deserialized: FbxLoaderSettings =
serde_json::from_str(&serialized).expect("Failed to deserialize");
// Check equality
assert_eq!(deserialized.load_meshes, original.load_meshes);
assert_eq!(deserialized.load_materials, original.load_materials);
assert_eq!(deserialized.load_cameras, original.load_cameras);
assert_eq!(deserialized.load_lights, original.load_lights);
assert_eq!(deserialized.include_source, original.include_source);
assert_eq!(
deserialized.convert_coordinates,
original.convert_coordinates
);
}
+146
View File
@@ -0,0 +1,146 @@
//! Tests for FBX types.
use bevy::prelude::*;
use bevy_ufbx::types::*;
use std::collections::HashMap;
#[test]
fn test_handedness_equality() {
assert_eq!(Handedness::Right, Handedness::Right);
assert_eq!(Handedness::Left, Handedness::Left);
assert_ne!(Handedness::Right, Handedness::Left);
}
#[test]
fn test_fbx_axis_system_creation() {
let axis_system = FbxAxisSystem {
up: Vec3::Y,
front: Vec3::Z,
handedness: Handedness::Right,
};
assert_eq!(axis_system.up, Vec3::Y);
assert_eq!(axis_system.front, Vec3::Z);
assert_eq!(axis_system.handedness, Handedness::Right);
}
#[test]
fn test_fbx_meta_default() {
let meta = FbxMeta::default();
assert!(meta.creator.is_none());
assert!(meta.creation_time.is_none());
assert!(meta.original_application.is_none());
}
#[test]
fn test_fbx_wrap_mode_equality() {
assert_eq!(FbxWrapMode::Repeat, FbxWrapMode::Repeat);
assert_eq!(FbxWrapMode::Clamp, FbxWrapMode::Clamp);
assert_ne!(FbxWrapMode::Repeat, FbxWrapMode::Clamp);
}
#[test]
fn test_fbx_texture_type_hash() {
use std::collections::HashSet;
let mut set = HashSet::new();
set.insert(FbxTextureType::BaseColor);
set.insert(FbxTextureType::Normal);
set.insert(FbxTextureType::Metallic);
assert!(set.contains(&FbxTextureType::BaseColor));
assert!(set.contains(&FbxTextureType::Normal));
assert!(set.contains(&FbxTextureType::Metallic));
assert!(!set.contains(&FbxTextureType::Roughness));
}
#[test]
fn test_fbx_light_type_equality() {
assert_eq!(FbxLightType::Directional, FbxLightType::Directional);
assert_eq!(FbxLightType::Point, FbxLightType::Point);
assert_eq!(FbxLightType::Spot, FbxLightType::Spot);
assert_ne!(FbxLightType::Point, FbxLightType::Spot);
}
#[test]
fn test_fbx_projection_mode_equality() {
assert_eq!(
FbxProjectionMode::Perspective,
FbxProjectionMode::Perspective
);
assert_eq!(
FbxProjectionMode::Orthographic,
FbxProjectionMode::Orthographic
);
assert_ne!(
FbxProjectionMode::Perspective,
FbxProjectionMode::Orthographic
);
}
#[test]
fn test_fbx_interpolation_equality() {
assert_eq!(FbxInterpolation::Constant, FbxInterpolation::Constant);
assert_eq!(FbxInterpolation::Linear, FbxInterpolation::Linear);
assert_eq!(FbxInterpolation::Cubic, FbxInterpolation::Cubic);
assert_ne!(FbxInterpolation::Linear, FbxInterpolation::Cubic);
}
#[test]
fn test_fbx_material_creation() {
let material = FbxMaterial {
name: "TestMaterial".to_string(),
base_color: Color::WHITE,
metallic: 0.5,
roughness: 0.7,
emission: Color::BLACK,
normal_scale: 1.0,
alpha: 1.0,
alpha_cutoff: 0.5,
double_sided: false,
textures: HashMap::new(),
};
assert_eq!(material.name, "TestMaterial");
assert_eq!(material.base_color, Color::WHITE);
assert_eq!(material.metallic, 0.5);
assert_eq!(material.roughness, 0.7);
assert!(!material.double_sided);
}
#[test]
fn test_fbx_light_creation() {
let light = FbxLight {
name: "TestLight".to_string(),
light_type: FbxLightType::Point,
color: Color::WHITE,
intensity: 100.0,
cast_shadows: true,
inner_angle: None,
outer_angle: None,
};
assert_eq!(light.name, "TestLight");
assert_eq!(light.light_type, FbxLightType::Point);
assert!(light.cast_shadows);
assert!(light.inner_angle.is_none());
}
#[test]
fn test_fbx_camera_creation() {
let camera = FbxCamera {
name: "TestCamera".to_string(),
projection_mode: FbxProjectionMode::Perspective,
field_of_view_deg: 60.0,
aspect_ratio: 1.777,
near_plane: 0.1,
far_plane: 1000.0,
focal_length_mm: 35.0,
};
assert_eq!(camera.name, "TestCamera");
assert_eq!(camera.projection_mode, FbxProjectionMode::Perspective);
assert_eq!(camera.field_of_view_deg, 60.0);
assert!((camera.aspect_ratio - 1.777).abs() < 0.001);
}
+96
View File
@@ -0,0 +1,96 @@
//! Tests for utility conversion functions.
use bevy::prelude::*;
use bevy_ufbx::utils::{convert_matrix, convert_transform};
#[test]
fn test_convert_matrix() {
// Create a simple ufbx matrix
let ufbx_matrix = ufbx::Matrix {
m00: 1.0,
m01: 0.0,
m02: 0.0,
m03: 10.0,
m10: 0.0,
m11: 1.0,
m12: 0.0,
m13: 20.0,
m20: 0.0,
m21: 0.0,
m22: 1.0,
m23: 30.0,
};
let mat4 = convert_matrix(&ufbx_matrix);
// Check that translation is preserved
assert_eq!(mat4.w_axis.x, 10.0);
assert_eq!(mat4.w_axis.y, 20.0);
assert_eq!(mat4.w_axis.z, 30.0);
assert_eq!(mat4.w_axis.w, 1.0);
// Check diagonal elements
assert_eq!(mat4.x_axis.x, 1.0);
assert_eq!(mat4.y_axis.y, 1.0);
assert_eq!(mat4.z_axis.z, 1.0);
}
#[test]
fn test_convert_transform() {
let ufbx_transform = ufbx::Transform {
translation: ufbx::Vec3 {
x: 1.0,
y: 2.0,
z: 3.0,
},
rotation: ufbx::Quat {
x: 0.0,
y: 0.0,
z: 0.0,
w: 1.0,
},
scale: ufbx::Vec3 {
x: 2.0,
y: 2.0,
z: 2.0,
},
};
let transform = convert_transform(&ufbx_transform);
assert_eq!(transform.translation, Vec3::new(1.0, 2.0, 3.0));
assert_eq!(transform.rotation, Quat::IDENTITY);
assert_eq!(transform.scale, Vec3::new(2.0, 2.0, 2.0));
}
#[test]
fn test_convert_transform_with_rotation() {
// Test with a 90-degree rotation around Y axis
let half_sqrt2 = 0.7071067811865476;
let ufbx_transform = ufbx::Transform {
translation: ufbx::Vec3 {
x: 0.0,
y: 0.0,
z: 0.0,
},
rotation: ufbx::Quat {
x: 0.0,
y: half_sqrt2,
z: 0.0,
w: half_sqrt2,
},
scale: ufbx::Vec3 {
x: 1.0,
y: 1.0,
z: 1.0,
},
};
let transform = convert_transform(&ufbx_transform);
// Check rotation is preserved
assert!((transform.rotation.x - 0.0).abs() < 0.001);
assert!((transform.rotation.y - half_sqrt2 as f32).abs() < 0.001);
assert!((transform.rotation.z - 0.0).abs() < 0.001);
assert!((transform.rotation.w - half_sqrt2 as f32).abs() < 0.001);
}