Showing preview only (431K chars total). Download the full file or copy to clipboard to get everything.
Repository: idanarye/bevy-yoleck
Branch: main
Commit: b832597b4775
Files: 58
Total size: 411.6 KB
Directory structure:
gitextract_d08yw1cr/
├── .cargo/
│ └── config.toml
├── .github/
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── MIGRATION-GUIDES.md
├── README.md
├── assets/
│ ├── levels2d/
│ │ ├── .gitkeep
│ │ └── example.yol
│ ├── levels3d/
│ │ ├── .gitkeep
│ │ └── example.yol
│ ├── levels_doors/
│ │ ├── entry.yol
│ │ ├── index.yoli
│ │ ├── room1.yol
│ │ ├── room2.yol
│ │ └── room3.yol
│ ├── models/
│ │ ├── planet.blend
│ │ ├── planet.glb
│ │ ├── spaceship.blend
│ │ └── spaceship.glb
│ ├── sprites/
│ │ ├── doorway.pxo
│ │ ├── fruits.pxo
│ │ └── player.pxo
│ └── these-assets-are-for-the-examples
├── examples/
│ ├── custom_camera3d.rs
│ ├── doors_to_other_levels.rs
│ ├── example2d.rs
│ └── example3d.rs
├── macros/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs
├── run-retrospective-crate-version-tagging.sh
├── src/
│ ├── auto_edit.rs
│ ├── console.rs
│ ├── editing.rs
│ ├── editor.rs
│ ├── editor_panels.rs
│ ├── editor_window.rs
│ ├── entity_management.rs
│ ├── entity_ref.rs
│ ├── entity_upgrading.rs
│ ├── entity_uuid.rs
│ ├── errors.rs
│ ├── exclusive_systems.rs
│ ├── knobs.rs
│ ├── level_files_manager.rs
│ ├── level_files_upgrading.rs
│ ├── level_index.rs
│ ├── lib.rs
│ ├── picking_helpers.rs
│ ├── populating.rs
│ ├── specs_registration.rs
│ ├── util.rs
│ ├── vpeol.rs
│ ├── vpeol_2d.rs
│ └── vpeol_3d.rs
└── tests/
└── upgrade_level_file.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .cargo/config.toml
================================================
[alias]
example2d = "run --example example2d --features _example2d_full"
example3d = "run --example example3d --features _example3d_full"
custom_camera3d = "run --example custom_camera3d --features _example3d_full"
doors_to_other_levels = "run --example doors_to_other_levels --features _doors_to_other_levels_full"
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on:
pull_request:
push:
branches: [main]
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
checks: write
jobs:
ci:
name: CI
needs: [test, clippy, docs]
runs-on: ubuntu-latest
steps:
- name: Done
run: exit 0
test:
name: Tests
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest]
rust: [1.92.0, nightly]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Install rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{ matrix.rust }}
- name: Ready cache
if: matrix.os == 'ubuntu-latest'
run: sudo chown -R $(whoami):$(id -ng) ~/.cargo/
- name: Install dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev libudev-dev
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Test
run: cargo test --verbose --all-features --features bevy/bevy_gltf -- --nocapture
fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.92.0
components: rustfmt
- name: Run fmt --all -- --check
run: cargo fmt --all -- --check
clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.92.0
components: clippy
- name: Install dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libudev-dev
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Run clippy --all-targets --
uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-targets --
docs:
name: Docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: 1.92.0
- name: Install dependencies
run: sudo apt-get update; sudo apt-get install --no-install-recommends libudev-dev
- name: Cache cargo
uses: actions/cache@v4
id: cache
with:
path: ~/.cargo
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Run doc tests
run: cargo test --doc --all-features --features bevy/bevy_gltf
- name: Check docs
run: cargo doc --no-deps --all-features --features bevy/x11
docs-and-demos-ghpages:
name: Update Docs and Demos in GitHub Pages
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- uses: jetli/wasm-bindgen-action@v0.2.0
with:
version: 'latest'
- uses: dtolnay/rust-toolchain@master
with:
targets: wasm32-unknown-unknown
toolchain: 1.92.0
- name: Build docs
env:
GITHUB_REPO: ${{ github.repository }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |-
cargo doc --no-deps --verbose --all-features --features bevy/webgl2,bevy/x11 &&
echo "<meta http-equiv=refresh content=0;url=bevy_yoleck/index.html>" > target/doc/index.html
required_features=$(
(
cargo metadata --no-deps --format-version 1 \
| jq '.packages[].targets[] | select(.kind == ["example"]) | .["required-features"][]' -r
echo bevy/webgl2
echo bevy/x11
) | tr '\n' ' '
)
RUSTFLAGS='--cfg getrandom_backend="wasm_js"' cargo build --examples --release --features "$required_features" --target wasm32-unknown-unknown
for demowasm in $(cd target/wasm32-unknown-unknown/release/examples; ls *.wasm | grep -v -); do
wasm-bindgen target/wasm32-unknown-unknown/release/examples/$demowasm --out-dir target/doc/demos/ --target web
cat > target/doc/demos/${demowasm%.*}.html <<EOF
<html lang="en-us">
<head>
<script type="module">
import init from './${demowasm%.*}.js';
var res = await init();
res.start();
</script>
</head>
<body>
<script>
document.body.addEventListener("contextmenu", (e) => {
e.preventDefault();
e.stopPropagation();
});
</script>
</body>
</html>
EOF
done
cp -R assets/ target/doc/demos/
- name: Add read permissions
run: |-
chmod --recursive +r target/doc
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: target/doc
deploy-ghpages:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: docs-and-demos-ghpages
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
================================================
FILE: .gitignore
================================================
/target
Cargo.lock
assets/levels2d/*.yol
assets/levels2d/*.yoli
!assets/levels2d/example.yol
assets/levels3d/*.yol
assets/levels3d/*.yoli
!assets/levels3d/example.yol
#IDES
/.vscode
# No ignored level files in levels_doors
================================================
FILE: CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## 0.31.0 - 2026-01-15
### Changed
- Upgrade Bevy to 0.18
## 0.30.0 - 2026-01-15
### Added
- Automatic UI generation for components using reflection and attributes.
- Supported numeric, boolean, string, vector, color, enum, option, list,
asset, and entity fields.
- `YoleckEntityRef` type with automatic UI, filtering, and runtime UUID
resolution.
- Drag and drop support for entity references: entities with UUID can now be
dragged from the entity list and dropped onto `YoleckEntityRef` fields in
the properties panel.
- Entity type filtering is automatically applied when dropping entities onto
entity reference fields with type constraints.
- `console_layer_factory` for routing Bevy logs into the Yoleck console.
- `YoleckConsoleLogHistory` for storing up to 1000 recent log entries.
- `YoleckConsoleState` for managing console UI state.
- `YoleckEditorBottomPanelSections` for extensible bottom-panel tabs.
- `Vpeol3dCameraMode` enum with variants: `Fps`, `Sidescroller`, `Topdown`,
`Custom(u32)`.
- `YoleckCameraChoices` resource for customizing available camera modes in 3D
editor.
- Support for custom camera modes with user-defined movement logic.
- Camera mode selector dropdown in editor top panel for switching between
camera modes.
- `Vpeol3dCameraControl::fps()` preset for FPS-style camera with full
rotation freedom.
- Scene gizmo for camera orientation.
- Translation gizmo for `vpeol_3d`.
- For all 3 world axes (X, Y, Z) by default.
- World/Local mode toggle for the translation gizmo in 3D editor top panel.
- Keyboard shortcut to delete selected entities: Press `Delete` key to remove
selected entity from the level.
- Copy/paste support for entities: Use `Ctrl+C` to copy and `Ctrl+V` to paste
entities with all their components and values.
- Cross-editor entity copying: Entities can be copied between different level
editors through system clipboard (opt in via the `arboard` feature)
- If `arboard` is not enabled the copy/paste will not be cross-editor
- Entity deletion via keyboard in addition to the existing UI button.
- Auto-selection of pasted entities: Newly pasted entities are automatically
selected for immediate editing.
- UI editing support for `Vpeol3dRotation` using Euler angles (X, Y, Z in
degrees)
- UI editing support for `Vpeol3dScale` with separate X, Y, Z drag values.
- UI editing support for `Vpeol2dRotatation` using degrees.
- UI editing support for `Vpeol2dScale` with separate X, Y drag values.
- `Vpeol3dSnapToPlane` to force an entity on a specific plane.
### Changed
- Improved editor ergonomics with better organized workspace instead of single
cluttered panel.
- Move camera with keyboard (WASD, with Q and E too for FPS camera) insted of
mouse dragging.
- Use registered systems instead of `YoleckEditorSection`.
- `YoleckRawEntry::data` is now a `Map<String, Value>` instead of a `Value`.
- Upgrade Rust edition to 2024.
- Update bevy_egui version to 0.38.
### Removed
- [**BREAKING**] Removed `Vpeol3dThirdAxisWithKnob` component (no longer needed
as all axes have knobs by default)
- Removed `plane_origin` field from `Vpeol3dCameraControl` (it was used for
movement by mouse-drag, which was dropped)
- Removed `YoleckEditorSection`.
## 0.29.0 - 2025-10-03
### Changed
- Upgrade Bevy to 0.17
- Rename:
- `YoleckSystemSet` -> `YoleckSystems`
- `VpeolSystemSet` -> `VpeolSystems`
## 0.28.0 - 2025-08-05
### Changed
- Update bevy_egui version to 0.36.
## 0.27.0 - 2025-07-03
### Changed
- Update bevy_egui version to 0.35.
## 0.26.1 - 2025-06-04
### Fixed
- Don't fail when adding `VpeolRouteClickTo` to a non-existing child.
## 0.26.0 - 2025-04-26
### Changed
- Upgrade Bevy to 0.16
- [**BREAKING**] Rename `YoleckEdit`'s method `get_single` and `get_single_mut`
to `single` and `single_mut` (to mirror a similar change in Bevy itself)
- Replace anyhow usage with `BevyError`.
## 0.25.0 - 2025-02-19
### Changed
- Update bevy_egui version to 0.33.
## 0.24.0 - 2025-01-09
### Changed
- Update bevy_egui version to 0.32.
## 0.23.0 - 2024-12-02
### Changed
- Update Bevy version to 0.15 and bevy_egui version to 0.31.
## 0.22.0 - 2024-07-06
### Changed
- Upgrade Bevy to 0.14 (and bevy_egui to 0.28)
## 0.21.0 - 2024-05-08
### Changed
- Update bevy_egui version to 0.27.
## 0.20.1 - 2024-04-01
### Fixed
- Enable bevy_egui's `render` feature, so that users won't need to load it
explicitly and can use the one reexported from Yoleck (fixes
https://github.com/idanarye/bevy-yoleck/issues/39)
## 0.20.0 - 2024-03-19
### Changed
- Update bevy_egui version to 0.26.
## 0.19.0 - 2024-02-27
### Changed
- Update Bevy version to 0.13 and bevy_egui version to 0.25.
- [**BREAKING**] Changed some API types to use Bevy's new math types. See the
[migration guide](MIGRATION-GUIDES.md#migrating-to-yoleck-019).
## 0.18.0 - 2024-02-18
### Changed
- Upgrade bevy_egui to 0.24.
### Fixed
- [**BREAKING**] Typo - `Rotatation` -> `Rotation` in Vpeol.
## 0.17.1 - 2024-01-14
### Fixed
- Use a proper `OR` syntax for the dual license.
## 0.17.0 - 2023-11-25
### Removed
- [**BREAKING**] The `YoleckLoadingCommand` resource is removed, in favor of a
`YoleckLoadLevel` component. See the [migration
guide](MIGRATION-GUIDES.md#migrating-to-yoleck-017).
- Note that unlike `YoleckLoadingCommand` that could load the level from
either an asset or a value, `YoleckLoadLevel` can only load from an asset.
If it is necessary to load a level from memory, add it to
`ResMut<Assets<YoleckRawLevel>>` first and pass the handle to
`YoleckLoadLevel`.
- [**BREAKING**] The `yoleck_populate_schedule_mut` method (which Yoleck was
adding as an extension on Bevy's `App`) is removed in favor of just using
`YoleckSchedule::Populate` directly.
### Added
- `YoleckEditableLevels` resource (accessible only from edit systems) that
provides the list of level file names.
- Entity reference with `YoleckEntityUuid` and `YoleckUuidRegistry`.
- Some picking helpers for handling entity references in the editor:
`vpeol_read_click_on_entity`, `yoleck_map_entity_to_uuid` and
`yoleck_exclusive_system_cancellable`.
- Load multiple levels with `YoleckLoadLevel` (which is a component, that can
be placed on multiple entities)
- Unload levels by removing the `YoleckKeepLevel` component from the entity
that was used to load the level - or by despawning that entity entirely.
- `YoleckSchedule::LevelLoaded` schedule for interfering with levels before
populating their entities.
- `VpeolRepositionLevel` component.
### Change
- `YoleckBelongsToLevel` now points to a level entity.
- `YoleckDirective::spawn_entity` needs to know which level entity to create
the component on.
## 0.16.0 - 2023-09-06
### Changed
- Upgrade Bevy to 0.12 (and bevy_egui to 0.23)
## 0.15.0 - 2023-10-15
### Changed
- Upgrade bevy_egui to 0.22
- [**BREAKING**] `YoleckUi` is a regular resource again. See the [migration
guide](MIGRATION-GUIDES.md#migrating-to-yoleck-013).
## 0.14.1 - 2023-07-30
### Fixed
- `Vpeol2dCameraControl` reversing the Y axis when panning and zooming.
Note that the implementation of this fix requires that the camera entity will
have the `VpeolCameraState` component - without it `Vpeol2dCameraControl`
will not work at all. I do not consider it a breaking change though, because:
1. The documentation do imply that you need `VpeolCameraState`.
2. `Vpeol3dCameraControl` was already requiring `VpeolCameraState`, and they
are supposed to be equivalent.
3. `vpeol_2d` is useless without `VpeolCameraState`, so I'm not expecting
anyone to not be using it just so that they can use the camera controls.
So having `Vpeol2dCameraControl` work without `VpeolCameraState` was an
undocumented feature, and I'm going to release this as a bugfix version, not
a minor version.
## 0.14.0 - 2023-07-18
### Changed
### Added
- `#[derive(Reflect)]` to several components. Requires the `bevy_reflect` flag.
- [**BREAKING**] Rename `YoleckRouteClickTo` to `VpeolRouteClickTo`.
## 0.13.0 - 2023-07-11
### Changed
- Upgrade Bevy to 0.11 (and bevy_egui to 0.21)
- [**BREAKING**] `YoleckUi` is now a non-`Send` resource. See the [migration
guide](MIGRATION-GUIDES.md#migrating-to-yoleck-013).
## 0.12.0 - 2023-06-20
### Added
- An exclusive systems mechanism for edit systems that operate alone and can
thus assume control over the input (e.g. mouse motion and clicks)
- Multiple selection with the Shift key, and `YoleckEdit` methods for editing
multiple entities.
### Changed
- When creating a new entity that uses `Vpeol*dPosition`, an exclusive system
will kick in to allow placing the entity with the mouse (instead of just
placing it in the origin and letting the user drag it from there)
## 0.11.0 - 2023-04-06
### Added
- `YoleckBelongsToLevel` for deciding which entities to despawn when the level
unloads/restarts. This is added automatically by Yoleck, but should also be
added to entities created by the game.
## 0.10.0 - 2023-03-28
### Changed
- Model detection now raycasts against the meshes in addition to the AABB.
### Added
- Supported for 2D meshes in vpeol_2d.
## 0.9.0 - 2023-03-27
### Changed
- [**BREAKING**] This entire release is a huge breaking change. See the
[migration guide](MIGRATION-GUIDES.md#migrating-to-yoleck-09).
- [**BREAKING**] Move to a new model, where each Yoleck entity can be composed
of multiple `YoleckComponent`s.
- [**BREAKING**] The syntax of edit systems and populate systems has
drastically changed.
### Added
- A mechanism for upgrading entity's data when their layout changes. See
`YoleckEntityUpgradingPlugin`. This can be used to upgrade old games to use
the new semantics introduced in this version.
- `vpeol_3d` is back in, without the dependencies and with better dragging.
- `yoleck::prelude`
- `yoleck::vpeol::prelude`
### Removed
- `vpeol_position_edit_adapter` and `VpeolTransform2dProjection`. Use `Vpeol2dPosition` instead.
## 0.8.0 - 2023-03-14
### Changed
- Add scroll area to editor window.
### Fixed
- Panic that happens sometimes when dragging an entity with children.
### Added
- `YoleckDirective::spawn_entity` for spawning entities from user code (e.g.
for creating entity duplication buttons)
## 0.7.0 - 2023-03-09
### Changed
- Upgrade Bevy to 0.10 (and bevy_egui to 0.20)
- [**BREAKING**] `VpeolSystemLabel` becomes `VpeolSystems`, and uses Bevy's
new system set semantics instead of the removed system label semantics. All
sets of that system are configured to run during the `EditorActive` state.
### Added
- `Anchor` is taken into account when vpeol_2d checks clicks on text (previous to
Bevy 0.10 it did not have an `Anchor` component, and just used top-left)
## 0.6.0 - 2023-03-06
### Changed
- [**BREAKING**] Vpeol names no longer container the "yoleck" prefix - so
`YoleckVpeolXYZ` becomes `VpeolXYZ` and `yoleck_vpeol_xyz` becomes
`vpeol_xyz`. Vpeol is enough to avoid conflicts.
- [**BREAKING**] `vpeol_2d` sends drag coordinates as `Vec3`, not `Vec2`.
- [**BREAKING**] `YoleckWillContainClickableChildren` is renamed to
`VpeolWillContainClickableChildren` and is no longer reexported by
`vpeol_2d`.
### Added
- [**BREAKING**] `VpeolCameraState` - must be placed on a camera in order for
vpoel to work.
- [**BREAKING**] `Vpeol2dCameraControl` - must be placed on a camera in order
for vpoel_2d to apply camera panning and scrolling.
## 0.5.0 - 2023-02-22
### Changed
- Update bevy-egui version to 0.19.
## 0.4.0 - 2022-11-14
### Changed
- Update Bevy version to 0.9 and bevy-egui version to 0.17.
### Added
- Ability to revert levels to their initial state:
- `Wipe Level` button for ne` levels.
- `REVERT` button for existing levels
- This is important because otherwise the only ways to select a different
level are to save the changes or restart the editor.
### Fixed
- Knobs remaining during playtest.
## 0.3.0 - 2022-08-18
### Changed
- Update Bevy version to 0.8 and bevy-egui version to 0.15.
### Removed
- **REGRESSION**: Removed `vpeol_3d` and `example3d`. They were depending on
crates that were slow to migrate to Bevy 0.8 (one of then has still not
released its Bevy 0.8 version when this changelog entry was written). Since
`vpeol_3d` was barely usable to begin with (the gizmo is not a good way to
move objects around - we need proper dragging! - and `bevy_mod_pickling`
required lots of hacks to play nice with Yoleck) it has been removed for now
and will be re-added in the future with less dependencies and better
interface.
### Fixed
- Use the correct transform when dragging child entities (#11)
### Added
- Knobs!
## 0.2.0 - 2022-06-09
### Added
- `YoleckVpeolSelectionCuePlugin` for adding a pulse effect to show the
selected entity in the viewport.
## 0.1.1 - 2022-06-02
### Fixed
- `vpeol_3d`: Entities sometimes getting deselected when cursor leaves egui area.
- `vpeol_3d`: Freshly created entities getting selected in Yoleck but Gizmo is not shown.
## 0.1.0 - 2022-06-01
### Added
- Building `YoleckTypeHandler`s to define the entity types.
- Editing entity structs with egui.
- Populating entities with components based on entity structs.
- Editor file manager.
- Level loading from files.
- Level index loading.
- `vpeol_2d` and `vpeol_3d`.
================================================
FILE: Cargo.toml
================================================
[workspace]
members = ["macros"]
[workspace.package]
edition = "2024"
authors = ["IdanArye <idanarye@gmail.com>", "dexsper <dexsperpro@gmail.com>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/idanarye/bevy-yoleck"
[package]
name = "bevy-yoleck"
description = "Your Own Level Editor Creation Kit"
version = "0.31.0"
edition.workspace = true
authors.workspace = true
license.workspace = true
repository.workspace = true
documentation = "https://docs.rs/bevy-yoleck"
readme = "README.md"
categories = ["game-development"]
keywords = ["bevy", "gamedev", "level-editor"]
exclude = ["assets"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bevy-yoleck-macros = { version = "0.10.0", path = "macros" }
bevy = { version = "^0.18", default-features = false, features = [
"bevy_state",
"bevy_window",
"bevy_asset",
"bevy_log",
"bevy_camera",
] }
bevy_egui = { version = "^0.39", default-features = false, features = [
"default_fonts",
"render",
] }
serde = "^1"
serde_json = "^1"
thiserror = "^2"
uuid = "1.9.1"
arboard = {version = "3.4", optional = true}
[features]
bevy_reflect = []
vpeol = []
vpeol_2d = ["vpeol", "bevy/bevy_text", "bevy/bevy_sprite", "bevy/png"]
vpeol_3d = ["vpeol", "bevy/bevy_pbr"]
# Support clipboard with the Arboard crate. Otherwise the clipboard will be internal.
arboard = ["dep:arboard"]
# Enable Wayland support in Arboard.
arboard_wayland = ["arboard", "arboard/wayland-data-control"]
_example2d_full = ["vpeol_2d", "bevy/bevy_gizmos", "bevy/bevy_sprite_render"]
_example3d_full = [
"vpeol_3d",
"bevy/bevy_scene",
"bevy/bevy_gltf",
"bevy/bevy_animation",
"bevy/ktx2",
"bevy/zstd_rust",
"bevy/tonemapping_luts",
"bevy/bevy_gizmos",
"bevy/reflect_auto_register",
"bevy/bevy_sprite_render",
]
_doors_to_other_levels_full = ["vpeol_2d", "bevy/bevy_sprite_render"]
[dev-dependencies]
bevy = { version = "^0.18", default-features = false, features = [
"bevy_sprite",
"x11",
"bevy_window",
"bevy_text",
"bevy_render",
] }
[[example]]
name = "example2d"
required-features = ["_example2d_full"]
[[example]]
name = "example3d"
required-features = ["_example3d_full"]
[[example]]
name = "custom_camera3d"
required-features = ["_example3d_full"]
[[example]]
name = "doors_to_other_levels"
required-features = ["_doors_to_other_levels_full"]
[package.metadata.docs.rs]
all-features = true
features = [
"bevy/x11", # required for bevy_egui
"bevy/bevy_gltf", # required for SceneRoot in vpeol_3d's doctests
]
================================================
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
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.
================================================
FILE: LICENSE-MIT
================================================
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: MIGRATION-GUIDES.md
================================================
# Migrating to Yoleck 0.19
## Using the new Bevy types
Bevy 0.13 introduces types for defining directions and planes, which can be used instead of vectors. Yoleck (mainly Vpeol) uses them now in its API. The conversion should be straightforward.
Specifically:
- `VpeolDragPlane` now uses `Plane3d`.
- `Vpeol3dPluginForEditor` also uses `Plane3d`.
- `Vpeol3dCameraControl` uses `Plane3d` for the camera drag plane, and
`Direction3d` for configuring the UP direction to maintain while rotating
the camera.
## `vpeol_read_click_on_entity`
Bevy 0.13 [split `WorldQuery` to `QueryData` and `FilterData`](https://bevyengine.org/learn/migration-guides/0-12-to-0-13/#split-worldquery-into-querydata-and-queryfilter) (though there is still a `WorldQuery` trait with some of that functionality). When you use `vpeol_read_click_on_entity`, the data passed to it is `QueryFilter`, not `QueryData` - which measn that if it's a component (which should usually be the case) you need `vpeol_read_click_on_entity::<Has<MyComponent>>` and not `vpeol_read_click_on_entity::<&MyComponent>` (which would have worked before)
# Migrating to Yoleck 0.17
## Loading levels
Instead of a `YoleckLoadingCommand` resource, level loading is now done via entities. This means that instead of loading a level like this:
```rust
fn load_level(
mut yoleck_loading_command: ResMut<YoleckLoadingCommand>,
asset_server: Res<AssetServer>,
) {
*yoleck_loading_command = YoleckLoadingCommand::FromAsset(asset_server.load("levels/my-level.yol"));
}
```
You should do it like this:
```rust
fn load_level(
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
commands.spawn(YoleckLoadLevel(asset_server.load("levels/my-level.yol")));
}
```
Note that `YoleckLoadLevel` does not provide an equivalent for `YoleckLoadingCommand::FromData`. If you need to load a level from a value, put that value in `Assets<YoleckRawLevel>` first.
## Clearing levels
Instead of despawning all the entities marked with `YoleckBelongsToLevel`:
```rust
fn unload_level(
query: Query<Entity, With<YoleckBelongsToLevel>>,
mut commands: Commands,
) {
for entity in query.iter() {
commands.entity(entity).despawn_recursive();
}
}
```
You should despawn the entities that represent the levels - the ones marked with `YoleckKeepLevel`:
```rust
fn unload_old_levels(
query: Query<Entity, With<YoleckKeepLevel>>,
mut commands: Commands,
) {
for entity in query.iter() {
commands.entity(entity).despawn_recursive();
}
}
```
Yoleck will automatically despawn (with `despawn_recursive`) all the entities that belong to these levels.
Note that it is also possible, if needed, to just remove the `YoleckKeepLevel` component from these entities to despawn their entities without despawning the level entities themselves.
## Changes in `YoleckBelongsToLevel`
`YoleckBelongsToLevel` now has a `pub level: Entity` field that specifies which level the entity belongs to. When unloading a level (by despawning a `YoleckKeepLevel` entity, or removing the `YoleckKeepLevel` component from it), the entities that will be despawned are the ones who's `YoleckBelongsToLevel` points at that level.
As before, if you create a component from a system and want it to be despawned when switching a level or restarting/finishing a playtest in the editor, it still needs the `YoleckBelongsToLevel` component. Except now you have to provide a level entity for it. Where should the level entity come from? Two options:
* It can be attached to an existing level, so that its lifetime will be bound to it. This is useful for entities that need to exist in the level's space - when despawning the level, we don't want these entities to remain.
The easiest way to achieve this is to use the `YoleckBelongsToLevel` of another component in that level. For example - say you have a treasure chest, and when the player shoots at it it opens up and a powerup pops from it for the player to pick up. Since the chest should already have a `YoleckBelongsToLevel` component, and since the system that spawns the powerup should already need to use some components of the chest entity, it should be easy to just clone the chest's `YoleckBelongsToLevel` and add it to the powerup spawning command.
* You can create a faux level and attach the entities to it. This is useful, for example, for a player character entity that can travel between levels. Just create a new entity with a `YoleckKeepLevel` component and add its `Entity` to the roaming entity inside a `YoleckBelongsToLevel` component.
Note that you can freely set an existing `YoleckBelongsToLevel` to point to different levels. So it might make more sense to switch the player character entity to different level as it travels between them than to associate it to some faux level. Both options are available.
## Adding populate systems
`yoleck_populate_schedule_mut` is removed - this no longer works:
```rust
app.yoleck_populate_schedule_mut().add_systems(my_populate_system);
```
Instead, just add the system on the `YoleckSchedule::Populate` schedule:
```rust
app.add_systems(YoleckSchedule::Populate, my_populate_system);
```
`yoleck_populate_schedule_mut` made ergonomic sense in Bevy 0.10, but since starting Bevy 0.11 one has to always specify the schedule, it is no longer that ergonomic to have this helper method.
# Migrating to Yoleck 0.15
## Accessing the YoleckUi
Now that https://github.com/emilk/egui/pull/3233 got in to egui 0.23, and bevy_egui 0.22 was released with that new version of egui, `YoleckUi` can be made a regular resource again.
`YoleckUi` can no longer be accessed with `NonSend`/`NonSendMut`, and must be accessed with the regular `Res`/`ResMut`.
# Migrating to Yoleck 0.13
## Accessing the YoleckUi
`YoleckUi` is now a non-`Send` resource, which means it can no longer be accessed as a regular `Res`/`ResMut`. It must now be accessed as `NonSend`/`NonSendMut`.
Hopefully once https://github.com/emilk/egui/issues/3148 is fixed (and gets in to bevy_egui) this can be changed back.
# Migrating to Yoleck 0.9
## Importing
Most of the commonly used stuff can be imported from the new prelude module:
```rust
use bevy_yoleck::prelude::*;
```
## Entity type definition and registration
Previously entity types were declared as struct:
```rust
#[derive(Clone, PartialEq, Serialize, Deserialize)]
struct Foo {
#[serde(default)]
bar: Bar,
#[serde(default)]
baz: Baz,
}
```
And registered with:
```rust
app.add_yoleck_handler({
YoleckTypeHandler::<Foo>::new("Foo")
.populate_with(populate_foo)
.edit_with(edit_foo)
});
```
Starting from 0.9, entities can be broken to multiple components:
```rust
#[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
struct Bar {
// ...
}
#[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
struct Baz {
// ...
}
```
You can still create one big component per entity type, but if there are data
fields that are shared between different entity types it's better to split them
out so that they can be edited with the same edit systems.
Instead of registering type handlers, register entity types:
```rust
app.add_yoleck_entity_type({
YoleckEntityType::new("Foo")
.with::<Bar>()
.with::<Baz>()
});
```
Unlike `YoleckTypeHandler`, that specifies the one data structure used by the
entity and all the edit and populate systems it'll have, `YoleckEntityType` can
specify multiple components and no systems. Systems are registered separately,
and are not bound to a single entity type:
```rust
app.add_yoleck_edit_system(edit_bar);
app.add_yoleck_edit_system(edit_baz);
app.yoleck_populate_schedule_mut().add_systems((
populate_bar,
populate_baz,
));
```
## Edit systems
In addition to the different method of registreation specified in the previous
section, the semantics of edit systems has also changed.
Previously, edit systems would use a closure:
```rust
fn edit_foo(mut edit: YoleckEdit<Foo>) {
edit.edit(|ctx, data, ui| {
// ...
});
}
```
Now they use something that acts like a query:
```rust
fn edit_foo(mut ui: ResMut<YoleckUi>, mut edit: YoleckEdit<&mut Foo>) {
let Ok(mut foo) = edit.get_single_mut() else { return };
// ...
}
```
The differences:
* Instead of a closure, we use `get_single_mut` to get the single entity. If no
entity is being edited, or if the edited entity does not match, we use
`return` to skip the rest of the edit system.
* In the future, when Yoleck will have multi-entity editing, `YoleckEdit`
will have `iter` and `iter_mut` for edit systems that can edit multiple
entities.
* Instead of getting the entity type directly as a generic parameter (`Foo`),
`YoleckEdit` gets it like Bevy `Query`s would (`&mut Foo`). In fact,
`YoleckEdit` can accept anything a Bevy query would accept, including filters
as a second parameter.
* Instead of getting the UI handle via a closure argument, we get it as a
resource in a separate `SystemParam` argument for the edit system function.
## Populate systems
In addition to the different method of registreation specified in an earlier
section, the semantics of populate systems has also changed.
Previously, populate systems would look like this:
```rust
fn populate_foo(mut populate: YoleckPopulate<Foo>) {
populate.populate(|ctx, data, &mut cmd| {
// ...
});
}
```
Populate systems still use closures, but they look different:
```rust
fn populate_foo(mut populate: YoleckPopulate<&Foo>) {
populate.populate(|ctx, &mut cmd, foo| {
// ...
});
}
```
The differences:
* Like `YoleckEdit`, `YoleckPopulate` also accepts query-like generic parameters.
* The command and data arguments to the closure switch places. Now the command
is the second argument and the data is the third.
* The data argument is actually what a Bevy query with the same generic
parameters as what the `YoleckPopulate` got would have yielded.
## Child entities
Previously, a populate system could freely use `cmd.despawn_descendants();`.
Now that there are multiple edit systems and their order is determined by a
scheduler, this should not be used, so instead populate systems should mark
child entities they create so that they can despawn them later (usually when
they replace them with freshly spawned ones):
```rust
fn populate_system(mut populate: YoleckPopulate<&MyComponent>, marking: YoleckMarking) {
populate.populate(|_ctx, mut cmd, my_component| {
marking.despawn_marked(&mut cmd);
cmd.with_children(|commands| {
let mut child = commands.spawn(marking.marker());
child.insert((
// relevant Bevy components
));
});
});
}
```
## Passed data
Previously, passed data would be accessed from the context argument of an edit system's closure:
## Knobs
Previously, knobs would be accessed from the context argument of an edit system's closure:
```rust
fn edit_foo(mut edit: YoleckEdit<Foo>, mut commands: Commands) {
edit.edit(|ctx, data, ui| {
let mut knob = ctx.knob(&mut commands, "knob-ident");
});
}
```
Starting from 0.9 knobs are accessed with a new `SystemParam` named `YoleckKnobs`:
```rust
fn edit_foo(mut edit: YoleckEdit<&mut Foo>, mut knobs: YoleckKnobs) {
let Ok(mut foo) = edit.get_single_mut() else { return };
let mut knob = knobs.knob("knob-ident");
}
```
The actual usage of the knob handle is unchained.
Note that knobs are not associated to a specific edited entity (although they
do reset when the selection changes). This was also true before 0.9, but is
more visible now that they are not accessed from the edit closure's `ctx`.
## Position manipulation with vpeol_2d
* Instead of `vpeol_position_edit_adapter`, use `Vpeol2dPosition` as a Yoleck component.
* Don't set the translation by yourself - let vpeol_2d do it.
* If you need to also set rotation and scale, use `Vpeol2dRotatation` and
`Vpeol2dScale`. vpeol_2d does not currently offer edit systems for them (it
only takes them into account in the populate system), so you'll still have to
write them yourself.
* `Vpeol2dPlugin` is split into two - `Vpeol2dPluginForEditor` and
`Vpeol2dPluginForGame`. Use the appropriate one based on how the process
started, just like you'd use the appropriate
`YoleckPluginForEditor`/`YoleckPluginForGame`.
================================================
FILE: README.md
================================================
[](https://github.com/idanarye/bevy-yoleck/actions)
[](https://crates.io/crates/bevy-yoleck)
[](https://idanarye.github.io/bevy-yoleck/)
[](https://docs.rs/bevy-yoleck/)
# Bevy YOLECK - Your Own Level Editor Creation Kit
Yoleck is a crate for having a game built with the Bevy game engine act as its
own level editor.
## Features
* Same executable can launch in either game mode or editor mode, depending on
the plugins added to the app.
* Write systems that create entities based on serializable structs - use same
systems for both loading the levels and visualizing them in the editor.
* Entity editing is done with egui widgets that edit these structs.
| * Automatic UI generation for components with support for numeric, boolean, string, vector, color, enum, option, list, asset, and entity fields.
| * Entity linking system with automatic UI, filtering, and runtime UUID resolution. Supports drag-and-drop.
* Visual scene gizmo for camera orientation and control.
* Support for external plugins that offer more visual editing.
* One simple such plugin - Vpeol is included in the crate. It provides basic
entity selection, positioning with mouse dragging, and basic camera
control. It has two variants behind feature flags - `vpeol_2d` and
`vpeol_3d`.
* A knobs mechanism for more visual editing.
* Playtest the levels inside the editor.
* Multiple entity selection in the editor with the Shift key.
* Optional console system for displaying logs in the UI |
## Examples:
```bash
git clone https://github.com/dexsper/bevy-yoleck-fork
cd bevy-yoleck
```
Then you can run the examples:
* 2D example:
```bash
cargo example2d
```
Or check out the WASM version: https://idanarye.github.io/bevy-yoleck/demos/example2d
https://user-images.githubusercontent.com/1149255/228007948-31a37b3f-7bd3-4a36-a3bc-4617d359c7c2.mp4
* 3D example:
```bash
cargo example3d
```
Or check out the WASM version: https://idanarye.github.io/bevy-yoleck/demos/example3d
https://user-images.githubusercontent.com/1149255/228008014-825ef02e-2edc-49f5-a15c-1fa6044f84de.mp4
* Multi-level example:
```bash
cargo doors_to_other_levels
```
Or check out the WASM version (gameplay only): https://idanarye.github.io/bevy-yoleck/demos/doors_to_other_levels
https://github.com/idanarye/bevy-yoleck/assets/1149255/590beba4-2ca5-4218-af52-143321bb5946
## File Format
Yoleck saves the levels in JSON files that have the `.yol` extension. A `.yol`
file's top level is a tuple (actually JSON array) of three values:
* File metadata - e.g. Yoleck version.
* Level data (placeholder - currently an empty object)
* List of entities.
Each entity is a tuple of two values:
* Entity metadata - e.g. its type.
* Entity componments - that's the user defined structs.
The reason tuples are used instead of objects is to ensure ordering - to
guarantee the metadata can be read before the data. This is important because
the metadata is needed to parse the data.
Yoleck generates another JSON file in the same directory as the `.yol` files
called `index.yoli`. The purpose of this file is to let the game know what
level are available to it (in WASM, for example, the asset server cannot look
at a directory's contents). The index file contains a tuple of two values:
* Index metadata - e.g. Yoleck version.
* List of objects, each contain a path to a level file relative to the index
file.
## Versions
| bevy | bevy-yoleck | bevy_egui |
|------|-------------|-----------|
| 0.18 | 0.31 | 0.39 |
| 0.17 | 0.30 | 0.38 |
| 0.17 | 0.29 | 0.37 |
| 0.16 | 0.28 | 0.36 |
| 0.16 | 0.27 | 0.35 |
| 0.16 | 0.26 | 0.34 |
| 0.15 | 0.25 | 0.33 |
| 0.15 | 0.24 | 0.32 |
| 0.15 | 0.23 | 0.31 |
| 0.14 | 0.22 | 0.28 |
| 0.13 | 0.21 | 0.27 |
| 0.13 | 0.20 | 0.26 |
| 0.13 | 0.19 | 0.25 |
| 0.12 | 0.18 | 0.24 |
| 0.12 | 0.16, 0.17 | 0.23 |
| 0.11 | 0.15 | 0.22 |
| 0.11 | 0.13 - 0.14 | 0.21 |
| 0.10 | 0.7 - 0.12 | 0.20 |
| 0.9 | 0.5, 0.6 | 0.19 |
| 0.9 | 0.4 | 0.17 |
| 0.8 | 0.3 | 0.15 |
| 0.7 | 0.1, 0.2 | 0.14 |
## License
Licensed under either of
* Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or http://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.
================================================
FILE: assets/levels2d/.gitkeep
================================================
================================================
FILE: assets/levels2d/example.yol
================================================
[{"format_version":2,"app_format_version":1},{},[[{"type":"Player","name":""},{"Vpeol2dPosition":[-309.3874206542969,81.44441223144531],"Vpeol2dRotatation":0.0}],[{"type":"Triangle","name":""},{"TriangleVertices":{"vertices":[[-12.283805847167969,-141.28375244140625],[211.94580078125,-151.37274169921875],[199.81985473632812,16.863494873046875]]},"Vpeol2dPosition":[-459.87017822265625,-29.312294006347656]}],[{"type":"FloatingText","name":"","uuid":"8acaa597-8c7d-4b82-8fd5-4eda44e24b5f"},{"TextContent":{"text":"Collect the fruit"},"TextLaserPointer":{"target":{}},"Vpeol2dPosition":[118.0838623046875,306.9156494140625],"Vpeol2dScale":[1.0,1.0]}],[{"type":"FloatingText","name":"","uuid":"14195c3b-e420-4fa4-bc59-7149a7c7f5d4"},{"TextContent":{"text":"Orange"},"TextLaserPointer":{"target":{"uuid":"e8f8d516-ca5f-41d2-99a6-1be029fdd0ee"}},"Vpeol2dPosition":[74.51683044433594,-226.31687927246094],"Vpeol2dScale":[0.75,0.75]}],[{"type":"Fruit","name":"","uuid":"e8f8d516-ca5f-41d2-99a6-1be029fdd0ee"},{"FruitType":{"index":1},"Vpeol2dPosition":[-3.697650909423828,-60.341732025146484]}],[{"type":"Fruit","name":"","uuid":"eb26f293-7548-4bcc-a268-871c80726fd3"},{"FruitType":{"index":2},"Vpeol2dPosition":[-265.73712158203125,-226.1751708984375]}],[{"type":"FloatingText","name":"","uuid":"e9f7c89f-f975-41e0-9ab0-30991e715877"},{"TextContent":{"text":"Grapes"},"TextLaserPointer":{"target":{"uuid":"eb26f293-7548-4bcc-a268-871c80726fd3"}},"Vpeol2dPosition":[-440.10369873046875,-230.0904998779297],"Vpeol2dScale":[0.75,0.75]}]]]
================================================
FILE: assets/levels3d/.gitkeep
================================================
================================================
FILE: assets/levels3d/example.yol
================================================
[{"format_version":2,"app_format_version":0},{},[[{"type":"Planet","name":"","uuid":"c8aa8fdd-5431-473c-8774-b069c95f794f"},{"Vpeol3dPosition":[-7.047080993652344,6.785710334777832,0.0],"Vpeol3dRotation":[0.0,0.0,0.0,1.0],"Vpeol3dScale":[1.0,1.0,1.0]}],[{"type":"Planet","name":"","uuid":"2d676a47-146f-49f0-bba7-cf58a8833b1f"},{"Vpeol3dPosition":[16.688783645629883,-3.0687923431396484,0.0],"Vpeol3dRotation":[0.0,0.0,0.0,1.0],"Vpeol3dScale":[1.0,1.0,1.0]}],[{"type":"Spaceship","name":""},{"SpaceshipSettings":{"enabled":true,"rotation_speed":2.0,"speed":2.0},"Vpeol3dPosition":[1.2451118230819702,-2.86102294921875e-6,21.062850952148438]}],[{"type":"PlanetPointer","name":""},{"LaserPointer":{"target":{"uuid":"c8aa8fdd-5431-473c-8774-b069c95f794f"}},"Vpeol3dPosition":[3.227558135986328,2.0,-29.523635864257812]}]]]
================================================
FILE: assets/levels_doors/entry.yol
================================================
[{"format_version":2,"app_format_version":0},{},[[{"type":"FloatingText","name":""},{"TextContent":{"text":"Start Room"},"Vpeol2dPosition":[28.116905212402344,132.0689239501953],"Vpeol2dScale":[1.0,1.0]}],[{"type":"Doorway","name":""},{"Doorway":{"marker":"s-1","target_level":"room1.yol"},"Vpeol2dPosition":[326.6886291503906,-15.409356117248535],"Vpeol2dRotatation":0.0}],[{"type":"Player","name":""},{"Vpeol2dPosition":[0.0,0.0]}]]]
================================================
FILE: assets/levels_doors/index.yoli
================================================
[{"format_version":1},[{"filename":"entry.yol"},{"filename":"room1.yol"},{"filename":"room2.yol"},{"filename":"room3.yol"}]]
================================================
FILE: assets/levels_doors/room1.yol
================================================
[{"format_version":2,"app_format_version":0},{},[[{"type":"Doorway","name":""},{"Doorway":{"marker":"s-1","target_level":"entry.yol"},"Vpeol2dPosition":[-341.4138488769531,-77.32525634765625],"Vpeol2dRotatation":-3.1367220878601074}],[{"type":"Doorway","name":""},{"Doorway":{"marker":"1-2","target_level":"room2.yol"},"Vpeol2dPosition":[13.468215942382812,371.9578857421875],"Vpeol2dRotatation":1.5801841020584106}],[{"type":"Doorway","name":""},{"Doorway":{"marker":"1-3","target_level":"room3.yol"},"Vpeol2dPosition":[23.59503173828125,-422.729248046875],"Vpeol2dRotatation":-1.5713714361190796}],[{"type":"Player","name":""},{"Vpeol2dPosition":[0.0,0.0]}],[{"type":"FloatingText","name":""},{"TextContent":{"text":"Room 1"},"Vpeol2dPosition":[3.049217939376831,77.6406021118164],"Vpeol2dScale":[1.0,1.0]}]]]
================================================
FILE: assets/levels_doors/room2.yol
================================================
[{"format_version":2,"app_format_version":0},{},[[{"type":"Doorway","name":""},{"Doorway":{"marker":"1-2","target_level":"room1.yol"},"Vpeol2dPosition":[-5.04287052154541,-384.5793762207031],"Vpeol2dRotatation":-1.5634950399398804}],[{"type":"Player","name":""},{"Vpeol2dPosition":[0.0,0.0]}],[{"type":"FloatingText","name":""},{"TextContent":{"text":"Room 2"},"Vpeol2dPosition":[-3.6070098876953125,-112.29154968261719],"Vpeol2dScale":[1.0,1.0]}]]]
================================================
FILE: assets/levels_doors/room3.yol
================================================
[{"format_version":2,"app_format_version":0},{},[[{"type":"Doorway","name":""},{"Doorway":{"marker":"1-3","target_level":"room1.yol"},"Vpeol2dPosition":[-4.219451904296875,364.6886291503906],"Vpeol2dRotatation":1.5755369663238525}],[{"type":"Player","name":""},{"Vpeol2dPosition":[0.0,0.0]}],[{"type":"FloatingText","name":""},{"TextContent":{"text":"Room 3"},"Vpeol2dPosition":[1.2645721435546875,150.7604217529297],"Vpeol2dScale":[1.0,1.0]}]]]
================================================
FILE: assets/these-assets-are-for-the-examples
================================================
================================================
FILE: examples/custom_camera3d.rs
================================================
use std::path::Path;
use bevy::color::palettes::css;
use bevy::prelude::*;
use bevy_egui::{EguiContexts, EguiPlugin};
use bevy_yoleck::YoleckEditMarker;
use bevy_yoleck::prelude::*;
use bevy_yoleck::vpeol::prelude::*;
/// Custom camera mode for isometric view with diagonal movement.
const CAMERA_MODE_ISOMETRIC: Vpeol3dCameraMode = Vpeol3dCameraMode::Custom(0);
/// Custom camera mode for orbital rotation around selected entities.
const CAMERA_MODE_ORBITAL: Vpeol3dCameraMode = Vpeol3dCameraMode::Custom(1);
fn main() {
let mut app = App::new();
app.add_plugins(DefaultPlugins);
let level = std::env::args().nth(1);
if let Some(level) = level {
app.add_plugins(EguiPlugin::default());
app.add_plugins(YoleckPluginForGame);
app.add_plugins(Vpeol3dPluginForGame);
app.add_systems(
Startup,
move |asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(
asset_server.load(Path::new("levels3d").join(&level)),
));
},
);
} else {
app.add_plugins(EguiPlugin::default());
app.add_plugins(YoleckPluginForEditor);
app.add_plugins(Vpeol3dPluginForEditor::topdown());
app.add_plugins(VpeolSelectionCuePlugin::default());
app.insert_resource(bevy_yoleck::YoleckEditorLevelsDirectoryPath(
Path::new(".").join("assets").join("levels3d"),
));
#[cfg(target_arch = "wasm32")]
app.add_systems(
Startup,
|asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(asset_server.load("levels3d/example.yol")));
},
);
app.insert_resource(
YoleckCameraChoices::default()
.choice_with_transform(
"Isometric",
{
let mut control = Vpeol3dCameraControl::fps();
control.mode = CAMERA_MODE_ISOMETRIC;
control.allow_rotation_while_maintaining_up = None;
control.wasd_movement_speed = 15.0;
control
},
Vec3::new(10.0, 10.0, 10.0),
Vec3::ZERO,
Vec3::Y,
)
.choice_with_transform(
"Orbital",
{
let mut control = Vpeol3dCameraControl::fps();
control.mode = CAMERA_MODE_ORBITAL;
control.allow_rotation_while_maintaining_up = None;
control.wasd_movement_speed = 0.0;
control.mouse_sensitivity = 0.005;
control
},
Vec3::new(0.0, 5.0, 15.0),
Vec3::ZERO,
Vec3::Y,
),
);
app.add_systems(
PostUpdate,
isometric_camera_movement.run_if(in_state(YoleckEditorState::EditorActive)),
);
app.add_systems(
PostUpdate,
orbital_camera_movement.run_if(in_state(YoleckEditorState::EditorActive)),
);
}
app.add_systems(Startup, (setup_camera, setup_scene));
app.add_yoleck_entity_type({
YoleckEntityType::new("Cube")
.with::<Vpeol3dPosition>()
.with::<Vpeol3dScale>()
.insert_on_init(|| IsCube)
});
app.add_systems(YoleckSchedule::Populate, populate_cube);
app.add_yoleck_entity_type({
YoleckEntityType::new("Sphere")
.with::<Vpeol3dPosition>()
.insert_on_init(|| IsSphere)
});
app.add_systems(YoleckSchedule::Populate, populate_sphere);
app.run();
}
fn setup_camera(mut commands: Commands) {
commands.spawn((
Camera3d::default(),
Transform::from_xyz(10.0, 10.0, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
VpeolCameraState::default(),
Vpeol3dCameraControl::topdown(),
));
commands.spawn((
DirectionalLight {
color: Color::WHITE,
illuminance: 10_000.0,
shadows_enabled: true,
..Default::default()
},
Transform::from_xyz(5.0, 10.0, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
fn setup_scene(
mut commands: Commands,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
) {
let mesh = mesh_assets.add(Mesh::from(
Plane3d {
normal: Dir3::Y,
half_size: Vec2::new(50.0, 50.0),
}
.mesh(),
));
let material = material_assets.add(Color::from(css::DARK_GRAY));
commands.spawn((
Mesh3d(mesh),
MeshMaterial3d(material),
Transform::from_xyz(0.0, -1.0, 0.0),
));
}
fn isometric_camera_movement(
mut egui_context: EguiContexts,
keyboard_input: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
mut cameras_query: Query<(&mut Transform, &Vpeol3dCameraControl)>,
) -> Result {
if egui_context.ctx_mut()?.wants_keyboard_input() {
return Ok(());
}
for (mut camera_transform, camera_control) in cameras_query.iter_mut() {
if camera_control.mode != CAMERA_MODE_ISOMETRIC {
continue;
}
let mut direction = Vec3::ZERO;
if keyboard_input.pressed(KeyCode::KeyW) {
direction += Vec3::new(-1.0, 0.0, -1.0);
}
if keyboard_input.pressed(KeyCode::KeyS) {
direction += Vec3::new(1.0, 0.0, 1.0);
}
if keyboard_input.pressed(KeyCode::KeyA) {
direction += Vec3::new(-1.0, 0.0, 1.0);
}
if keyboard_input.pressed(KeyCode::KeyD) {
direction += Vec3::new(1.0, 0.0, -1.0);
}
if keyboard_input.pressed(KeyCode::KeyQ) {
direction += Vec3::Y;
}
if keyboard_input.pressed(KeyCode::KeyE) {
direction += Vec3::NEG_Y;
}
if direction != Vec3::ZERO {
direction = direction.normalize();
let speed_multiplier = if keyboard_input.pressed(KeyCode::ShiftLeft) {
2.0
} else {
1.0
};
camera_transform.translation += direction
* camera_control.wasd_movement_speed
* speed_multiplier
* time.delta_secs();
}
}
Ok(())
}
fn orbital_camera_movement(
keyboard_input: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
mut cameras_query: Query<(&mut Transform, &Vpeol3dCameraControl)>,
selected_entities: Query<&GlobalTransform, With<YoleckEditMarker>>,
) {
for (mut camera_transform, camera_control) in cameras_query.iter_mut() {
if camera_control.mode != CAMERA_MODE_ORBITAL {
continue;
}
let look_at = if let Some(selected_transform) = selected_entities.iter().next() {
selected_transform.translation()
} else {
Vec3::ZERO
};
let mut orbit_speed = 0.0;
if keyboard_input.pressed(KeyCode::KeyA) {
orbit_speed += 1.0;
}
if keyboard_input.pressed(KeyCode::KeyD) {
orbit_speed -= 1.0;
}
if orbit_speed != 0.0 {
let rotation = Quat::from_axis_angle(Vec3::Y, orbit_speed * time.delta_secs());
let offset = camera_transform.translation - look_at;
camera_transform.translation = look_at + rotation * offset;
camera_transform.look_at(look_at, Vec3::Y);
}
let mut zoom = 0.0;
if keyboard_input.pressed(KeyCode::KeyW) {
zoom -= 1.0;
}
if keyboard_input.pressed(KeyCode::KeyS) {
zoom += 1.0;
}
if zoom != 0.0 {
let direction = (camera_transform.translation - look_at).normalize();
camera_transform.translation += direction * zoom * 10.0 * time.delta_secs();
}
camera_transform.look_at(look_at, Vec3::Y);
}
}
#[derive(Component)]
struct IsCube;
fn populate_cube(
mut populate: YoleckPopulate<(), With<IsCube>>,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut mesh: Local<Option<Handle<Mesh>>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
mut material: Local<Option<Handle<StandardMaterial>>>,
) {
populate.populate(|ctx, mut cmd, ()| {
cmd.insert(VpeolWillContainClickableChildren);
if ctx.is_first_time() {
let mesh = mesh
.get_or_insert_with(|| {
mesh_assets.add(Mesh::from(Cuboid::from_size(Vec3::splat(2.0))))
})
.clone();
let material = material
.get_or_insert_with(|| material_assets.add(Color::from(css::BLUE)))
.clone();
cmd.insert((Mesh3d(mesh), MeshMaterial3d(material)));
}
});
}
#[derive(Component)]
struct IsSphere;
fn populate_sphere(
mut populate: YoleckPopulate<(), With<IsSphere>>,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut mesh: Local<Option<Handle<Mesh>>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
mut material: Local<Option<Handle<StandardMaterial>>>,
) {
populate.populate(|ctx, mut cmd, ()| {
cmd.insert(VpeolWillContainClickableChildren);
if ctx.is_first_time() {
let mesh = mesh
.get_or_insert_with(|| mesh_assets.add(Mesh::from(Sphere { radius: 1.0 })))
.clone();
let material = material
.get_or_insert_with(|| material_assets.add(Color::from(css::RED)))
.clone();
cmd.insert((Mesh3d(mesh), MeshMaterial3d(material)));
}
});
}
================================================
FILE: examples/doors_to_other_levels.rs
================================================
use std::path::Path;
use bevy::color::palettes::css;
use bevy::math::Affine3A;
use bevy::platform::collections::HashSet;
use bevy::prelude::*;
use bevy_egui::{EguiPlugin, egui};
use bevy_yoleck::vpeol::prelude::*;
use bevy_yoleck::{YoleckEditableLevels, prelude::*};
use serde::{Deserialize, Serialize};
fn main() {
let mut app = App::new();
app.add_plugins(DefaultPlugins);
let level = if cfg!(target_arch = "wasm32") {
Some("entry.yol".to_owned())
} else {
std::env::args().nth(1)
};
app.add_plugins(EguiPlugin::default());
if let Some(level) = level {
app.add_plugins(YoleckPluginForGame);
app.add_plugins(Vpeol2dPluginForGame);
app.add_systems(
Startup,
move |asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(
asset_server.load(Path::new("levels_doors").join(&level)),
));
},
);
} else {
app.add_plugins(YoleckPluginForEditor);
app.add_plugins(Vpeol2dPluginForEditor);
app.add_plugins(VpeolSelectionCuePlugin::default());
app.insert_resource(bevy_yoleck::YoleckEditorLevelsDirectoryPath(
Path::new(".").join("assets").join("levels_doors"),
));
}
app.add_systems(Startup, setup_camera);
app.add_yoleck_entity_type({
YoleckEntityType::new("Player")
.with::<Vpeol2dPosition>()
.insert_on_init(|| IsPlayer)
});
app.add_systems(YoleckSchedule::Populate, populate_player);
app.add_yoleck_entity_type({
YoleckEntityType::new("FloatingText")
.with::<Vpeol2dPosition>()
.with::<Vpeol2dScale>()
.with::<TextContent>()
});
app.add_yoleck_edit_system(edit_text);
app.add_systems(YoleckSchedule::Populate, populate_text);
app.add_yoleck_entity_type({
YoleckEntityType::new("Doorway")
.with::<Vpeol2dPosition>()
.with::<Vpeol2dRotatation>()
.with::<Doorway>()
});
app.add_yoleck_edit_system(edit_doorway_rotation);
app.add_yoleck_edit_system(edit_doorway);
app.add_systems(YoleckSchedule::Populate, populate_doorway);
app.add_systems(Update, set_doorways_sprite_index);
app.add_systems(
YoleckSchedule::LevelLoaded,
(
handle_player_entity_when_level_loads,
position_level_from_opened_door,
),
);
app.add_systems(
Update,
(
control_camera,
control_player,
handle_door_opening,
close_old_doors,
)
.run_if(in_state(YoleckEditorState::GameActive)),
);
app.run();
}
fn setup_camera(mut commands: Commands) {
commands.spawn((
Camera2d,
Transform::from_xyz(0.0, 0.0, 100.0).with_scale(2.0 * (Vec3::X + Vec3::Y) + Vec3::Z),
VpeolCameraState::default(),
Vpeol2dCameraControl::default(),
));
}
#[derive(Component)]
struct IsPlayer;
fn populate_player(
mut populate: YoleckPopulate<(), With<IsPlayer>>,
asset_server: Res<AssetServer>,
mut texture_cache: Local<Option<Handle<Image>>>,
) {
populate.populate(|_ctx, mut cmd, ()| {
cmd.insert(Sprite {
image: texture_cache
.get_or_insert_with(|| asset_server.load("sprites/player.png"))
.clone(),
custom_size: Some(Vec2::new(100.0, 100.0)),
..Default::default()
});
});
}
fn control_camera(
player_query: Query<&GlobalTransform, With<IsPlayer>>,
mut camera_query: Query<&mut Transform, With<Camera>>,
time: Res<Time>,
) {
if player_query.is_empty() {
return;
}
let position_to_track = player_query.iter().map(|t| t.translation()).sum::<Vec3>()
/ player_query.iter().len() as f32;
for mut camera_transform in camera_query.iter_mut() {
let displacement = position_to_track - camera_transform.translation;
if displacement.length_squared() < 10000.0 {
camera_transform.translation +=
displacement.clamp_length_max(100.0 * time.delta_secs());
} else {
camera_transform.translation +=
displacement.clamp_length_max(800.0 * time.delta_secs());
}
}
}
fn control_player(
mut player_query: Query<&mut Transform, With<IsPlayer>>,
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
) {
let mut velocity = Vec3::ZERO;
if input.pressed(KeyCode::ArrowUp) {
velocity += Vec3::Y;
}
if input.pressed(KeyCode::ArrowDown) {
velocity -= Vec3::Y;
}
if input.pressed(KeyCode::ArrowLeft) {
velocity -= Vec3::X;
}
if input.pressed(KeyCode::ArrowRight) {
velocity += Vec3::X;
}
velocity *= 800.0;
for mut player_transform in player_query.iter_mut() {
player_transform.translation += velocity * time.delta_secs();
}
}
#[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
struct TextContent {
text: String,
}
fn edit_text(
mut ui: ResMut<YoleckUi>,
mut edit: YoleckEdit<(&mut TextContent, &mut Vpeol2dScale)>,
) {
let Ok((mut content, mut scale)) = edit.single_mut() else {
return;
};
ui.text_edit_multiline(&mut content.text);
// TODO: do this in vpeol_2d?
ui.add(egui::Slider::new(&mut scale.0.x, 0.5..=5.0).logarithmic(true));
scale.0.y = scale.0.x;
}
fn populate_text(mut populate: YoleckPopulate<&TextContent>, asset_server: Res<AssetServer>) {
populate.populate(|ctx, mut cmd, content| {
let text;
let color;
if ctx.is_in_editor() && content.text.chars().all(|c| c.is_whitespace()) {
text = "<TEXT>".to_owned();
color = css::WHITE.with_alpha(0.25);
} else {
text = content.text.clone();
color = css::WHITE;
};
cmd.insert((
Text2d(text),
TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 72.0,
..Default::default()
},
TextColor(color.into()),
));
});
}
#[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent, Debug)]
struct Doorway {
target_level: String,
marker: String,
}
fn edit_doorway(
mut ui: ResMut<YoleckUi>,
mut edit: YoleckEdit<&mut Doorway>,
levels: Res<YoleckEditableLevels>,
) {
let Ok(mut doorway) = edit.single_mut() else {
return;
};
ui.horizontal(|ui| {
egui::ComboBox::from_id_salt("doorway-level")
.selected_text(
Some(doorway.target_level.as_str())
.filter(|l| !l.is_empty())
.unwrap_or("<target level>"),
)
.show_ui(ui, |ui| {
for level in levels.names() {
ui.selectable_value(&mut doorway.target_level, level.to_owned(), level);
}
});
egui::TextEdit::singleline(&mut doorway.marker)
.hint_text("<marker>")
.show(ui);
});
}
fn edit_doorway_rotation(
mut ui: ResMut<YoleckUi>,
mut edit: YoleckEdit<(&Vpeol2dPosition, &mut Vpeol2dRotatation), With<Doorway>>,
mut knobs: YoleckKnobs,
) {
let Ok((Vpeol2dPosition(position), mut rotation)) = edit.single_mut() else {
return;
};
use std::f32::consts::PI;
ui.add(egui::Slider::new(&mut rotation.0, PI..=-PI).prefix("Angle: "));
// TODO: do this in vpeol_2d?
let mut rotate_knob = knobs.knob("rotate");
let knob_position = position.extend(1.0) + Quat::from_rotation_z(rotation.0) * (75.0 * Vec3::X);
rotate_knob.cmd.insert((
Sprite::from_color(css::PURPLE, Vec2::new(30.0, 30.0)),
Transform::from_translation(knob_position),
GlobalTransform::from(Transform::from_translation(knob_position)),
));
if let Some(rotate_to) = rotate_knob.get_passed_data::<Vec3>() {
rotation.0 = Vec2::X.angle_to(rotate_to.truncate() - *position);
}
}
fn populate_doorway(
mut populate: YoleckPopulate<(), With<Doorway>>,
asset_server: Res<AssetServer>,
mut asset_handle_cache: Local<Option<(Handle<Image>, Handle<TextureAtlasLayout>)>>,
mut texture_atlas_layout_assets: ResMut<Assets<TextureAtlasLayout>>,
) {
populate.populate(|_ctx, mut cmd, ()| {
let (image, texture_atlas_layout) = asset_handle_cache
.get_or_insert_with(|| {
(
asset_server.load("sprites/doorway.png"),
texture_atlas_layout_assets.add(TextureAtlasLayout::from_grid(
UVec2::new(64, 64),
1,
2,
None,
None,
)),
)
})
.clone();
cmd.insert(Sprite {
image,
custom_size: Some(Vec2::new(100.0, 100.0)),
texture_atlas: Some(TextureAtlas {
layout: texture_atlas_layout,
index: 0,
}),
..Default::default()
});
});
}
fn set_doorways_sprite_index(mut query: Query<(&mut Sprite, Has<DoorIsOpen>), With<Doorway>>) {
for (mut sprite, door_is_open) in query.iter_mut() {
if let Some(texture_atlas) = sprite.texture_atlas.as_mut() {
texture_atlas.index = if door_is_open { 1 } else { 0 };
}
}
}
#[derive(Component)]
struct LevelFromOpenedDoor {
exit_door: Entity,
}
#[derive(Component)]
struct PlayerHoldingLevel;
fn handle_player_entity_when_level_loads(
levels_query: Query<Has<LevelFromOpenedDoor>, With<YoleckLevelJustLoaded>>,
mut players_query: Query<(Entity, &mut YoleckBelongsToLevel, &Vpeol2dPosition), With<IsPlayer>>,
mut commands: Commands,
mut camera_query: Query<&mut Transform, With<Camera>>,
) {
for (player_entity, mut belongs_to_level, player_position) in players_query.iter_mut() {
let Ok(is_level_from_opened_door) = levels_query.get(belongs_to_level.level) else {
continue;
};
if is_level_from_opened_door {
commands.entity(player_entity).despawn();
} else {
belongs_to_level.level = commands
.spawn((
// So that the player entity will be removed when finishing a playtest in the
// editor:
YoleckKeepLevel,
// So that we won't remove that level when unloading old rooms:
PlayerHoldingLevel,
))
.id();
let translation_for_camera = player_position.0.extend(100.0);
for mut camera_transform in camera_query.iter_mut() {
*camera_transform = Transform {
translation: translation_for_camera,
rotation: Quat::IDENTITY,
scale: 2.0 * (Vec3::X + Vec3::Y) + Vec3::Z,
};
}
}
}
}
#[derive(Component)]
struct DoorIsOpen;
#[derive(Component)]
struct DoorConnectsTo(Entity);
fn handle_door_opening(
players_query: Query<&GlobalTransform, With<IsPlayer>>,
doors_query: Query<
(Entity, &YoleckBelongsToLevel, &GlobalTransform, &Doorway),
Without<DoorIsOpen>,
>,
mut commands: Commands,
asset_server: Res<AssetServer>,
levels_query: Query<Entity, (With<YoleckKeepLevel>, Without<PlayerHoldingLevel>)>,
) {
for player_transform in players_query.iter() {
for (door_entity, belongs_to_level, door_transform, doorway) in doors_query.iter() {
let distance_sq = player_transform
.translation()
.distance_squared(door_transform.translation());
if distance_sq < 10000.0 {
for level_entity in levels_query.iter() {
if level_entity != belongs_to_level.level {
commands.entity(level_entity).despawn();
}
}
commands.entity(door_entity).insert(DoorIsOpen);
commands.spawn((
YoleckLoadLevel(
asset_server.load(format!("levels_doors/{}", doorway.target_level)),
),
LevelFromOpenedDoor {
exit_door: door_entity,
},
));
}
}
}
}
fn position_level_from_opened_door(
levels_query: Query<(Entity, &LevelFromOpenedDoor), With<YoleckLevelJustLoaded>>,
doors_query: Query<(
Entity,
&YoleckBelongsToLevel,
Option<&GlobalTransform>,
&Doorway,
&Vpeol2dPosition,
&Vpeol2dRotatation,
)>,
mut commands: Commands,
) {
for (level_entity, level_from_opened_door) in levels_query.iter() {
let Ok((_, _, Some(exit_door_transform), exit_doorway, _, _)) =
doors_query.get(level_from_opened_door.exit_door)
else {
continue;
};
let exit_door_affine = exit_door_transform.affine();
let (entry_door_entity, _, _, _, entry_door_position, entry_door_rotation) = doors_query
.iter()
.find(|(_, belongs_to_level, _, entry_doorway, _, _)| {
belongs_to_level.level == level_entity
&& entry_doorway.marker == exit_doorway.marker
})
.expect(&format!(
"Cannot find a door marked as {:?} in {:?}",
exit_doorway.marker, exit_doorway.target_level
));
let entry_door_affine = Affine3A::from_rotation_translation(
Quat::from_rotation_z(entry_door_rotation.0),
entry_door_position.0.extend(0.0),
);
let rotate_door_around = Affine3A::from_rotation_translation(
Quat::from_rotation_z(std::f32::consts::PI),
100.0 * Vec3::X,
);
let level_transformation =
exit_door_affine * rotate_door_around * entry_door_affine.inverse();
let level_transformation = Transform::from_matrix(level_transformation.into());
commands
.entity(level_from_opened_door.exit_door)
.insert(DoorConnectsTo(entry_door_entity));
commands
.entity(entry_door_entity)
.insert((DoorIsOpen, DoorConnectsTo(level_from_opened_door.exit_door)));
commands
.entity(level_entity)
.insert(VpeolRepositionLevel(level_transformation));
}
}
fn close_old_doors(
mut removed_doors: RemovedComponents<DoorConnectsTo>,
doors_query: Query<(Entity, &DoorConnectsTo)>,
mut commands: Commands,
) {
if removed_doors.is_empty() {
return;
}
let removed_doors = removed_doors.read().collect::<HashSet<Entity>>();
for (door_entity, door_connects_to) in doors_query.iter() {
if removed_doors.contains(&door_connects_to.0) {
commands
.entity(door_entity)
.remove::<(DoorIsOpen, DoorConnectsTo)>();
}
}
}
================================================
FILE: examples/example2d.rs
================================================
use std::path::Path;
use bevy::color::palettes::css;
use bevy::ecs::system::SystemState;
use bevy::mesh::Indices;
use bevy::prelude::*;
use bevy::render::render_resource::PrimitiveTopology;
use bevy::{asset::RenderAssetUsages, log::LogPlugin};
use bevy_egui::{EguiContexts, EguiPlugin, egui};
use bevy_yoleck::YoleckDirective;
use bevy_yoleck::prelude::*;
use bevy_yoleck::vpeol::prelude::*;
use serde::{Deserialize, Serialize};
fn main() {
let mut app = App::new();
app.add_plugins(DefaultPlugins.set(LogPlugin {
custom_layer: bevy_yoleck::console_layer_factory,
..default()
}));
let level = std::env::args().nth(1);
if let Some(level) = level {
app.add_plugins(EguiPlugin::default());
app.add_plugins(YoleckPluginForGame);
app.add_plugins(bevy_yoleck::vpeol_2d::Vpeol2dPluginForGame);
app.add_systems(
Startup,
move |asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(
asset_server.load(Path::new("levels2d").join(&level)),
));
},
);
} else {
app.add_plugins(EguiPlugin::default());
app.add_plugins(YoleckPluginForEditor);
app.insert_resource(bevy_yoleck::YoleckEditorLevelsDirectoryPath(
Path::new(".").join("assets").join("levels2d"),
));
app.add_plugins(Vpeol2dPluginForEditor);
app.add_plugins(VpeolSelectionCuePlugin::default());
#[cfg(target_arch = "wasm32")]
app.add_systems(
Startup,
|asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(asset_server.load("levels2d/example.yol")));
},
);
}
app.add_plugins(YoleckEntityUpgradingPlugin {
app_format_version: 1,
});
app.add_systems(Startup, (setup_camera, setup_assets));
// ========================================================================
// Player
// ========================================================================
app.add_yoleck_entity_type({
YoleckEntityType::new("Player")
.with::<Vpeol2dPosition>()
.with::<Vpeol2dRotatation>()
.insert_on_init(|| IsPlayer)
});
app.add_yoleck_edit_system(edit_player);
app.add_systems(YoleckSchedule::Populate, populate_player);
app.add_yoleck_entity_upgrade_for(1, "Player", |data| {
let mut old_data = data.remove("Player").unwrap();
data["Vpeol2dPosition"] = old_data.get_mut("position").unwrap().take();
});
// ========================================================================
// Fruit
// ========================================================================
app.add_yoleck_entity_type({
YoleckEntityType::new("Fruit")
.with_uuid()
.with::<Vpeol2dPosition>()
.with::<FruitType>()
});
app.add_yoleck_edit_system(duplicate_fruit);
app.add_yoleck_edit_system(edit_fruit_type);
app.add_systems(YoleckSchedule::Populate, populate_fruit);
app.add_yoleck_entity_upgrade(1, |type_name, data| {
if type_name != "Fruit" {
return;
}
let mut old_data = data.remove("Fruit").unwrap();
data["Vpeol2dPosition"] = old_data.get_mut("position").unwrap().take();
data["FruitType"] = serde_json::json!({
"index": old_data.get_mut("fruit_index").unwrap().take(),
});
});
// ========================================================================
// FloatingText
// ========================================================================
app.add_yoleck_entity_type({
YoleckEntityType::new("FloatingText")
.with_uuid()
.with::<Vpeol2dPosition>()
.with::<Vpeol2dScale>()
.with::<TextContent>()
.with::<TextLaserPointer>()
});
app.add_yoleck_auto_edit::<TextContent>();
app.add_yoleck_auto_edit::<TextLaserPointer>();
app.add_systems(YoleckSchedule::Populate, populate_text);
app.add_yoleck_entity_upgrade(1, |type_name, data| {
if type_name != "FloatingText" {
return;
}
let mut old_data = data.remove("FloatingText").unwrap();
data["Vpeol2dPosition"] = old_data.get_mut("position").unwrap().take();
data["TextContent"] = serde_json::json!({
"text": old_data.get_mut("text").unwrap().take(),
});
data["Vpeol2dScale"] = serde_json::to_value(
Vec2::ONE * old_data.get_mut("scale").unwrap().take().as_f64().unwrap() as f32,
)
.unwrap();
});
// ========================================================================
// Triangle
// ========================================================================
app.add_yoleck_entity_type({
YoleckEntityType::new("Triangle")
.with::<Vpeol2dPosition>()
.with::<TriangleVertices>()
});
app.add_yoleck_edit_system(edit_triangle);
app.add_systems(YoleckSchedule::Populate, populate_triangle);
// ========================================================================
// Common systems
// ========================================================================
app.add_systems(Update, draw_laser_pointers);
app.add_systems(
Update,
(control_player, eat_fruits).run_if(in_state(YoleckEditorState::GameActive)),
);
app.run();
}
// ============================================================================
// Setup
// ============================================================================
fn setup_camera(mut commands: Commands) {
commands.spawn((
Camera2d,
Transform::from_xyz(0.0, 0.0, 100.0),
VpeolCameraState::default(),
Vpeol2dCameraControl::default(),
));
}
fn setup_assets(world: &mut World) {
world.init_resource::<GameAssets>();
}
#[derive(Resource)]
struct GameAssets {
fruits_sprite_sheet_texture: Handle<Image>,
fruits_sprite_sheet_layout: Handle<TextureAtlasLayout>,
fruits_sprite_sheet_egui: (egui::TextureId, Vec<egui::Rect>),
font: Handle<Font>,
}
impl FromWorld for GameAssets {
fn from_world(world: &mut World) -> Self {
let mut system_state = SystemState::<(
Res<AssetServer>,
ResMut<Assets<TextureAtlasLayout>>,
EguiContexts,
)>::new(world);
let (asset_server, mut texture_atlas_layout_assets, mut egui_context) =
system_state.get_mut(world);
let fruits_atlas_texture = asset_server.load("sprites/fruits.png");
let fruits_atlas_layout =
TextureAtlasLayout::from_grid(UVec2::new(64, 64), 3, 1, None, None);
let fruits_egui = {
(
egui_context.add_image(bevy_egui::EguiTextureHandle::Strong(
fruits_atlas_texture.clone(),
)),
fruits_atlas_layout
.textures
.iter()
.map(|rect| {
[
[
rect.min.x as f32 / fruits_atlas_layout.size.x as f32,
rect.min.y as f32 / fruits_atlas_layout.size.y as f32,
]
.into(),
[
rect.max.x as f32 / fruits_atlas_layout.size.x as f32,
rect.max.y as f32 / fruits_atlas_layout.size.y as f32,
]
.into(),
]
.into()
})
.collect(),
)
};
Self {
fruits_sprite_sheet_texture: fruits_atlas_texture,
fruits_sprite_sheet_layout: texture_atlas_layout_assets.add(fruits_atlas_layout),
fruits_sprite_sheet_egui: fruits_egui,
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
}
}
}
// ============================================================================
// Player
// ============================================================================
#[derive(Component)]
struct IsPlayer;
fn populate_player(
mut populate: YoleckPopulate<(), With<IsPlayer>>,
asset_server: Res<AssetServer>,
mut texture_cache: Local<Option<Handle<Image>>>,
) {
populate.populate(|_ctx, mut cmd, ()| {
cmd.insert(Sprite {
image: texture_cache
.get_or_insert_with(|| asset_server.load("sprites/player.png"))
.clone(),
custom_size: Some(Vec2::new(100.0, 100.0)),
..Default::default()
});
});
}
fn edit_player(
mut ui: ResMut<YoleckUi>,
mut edit: YoleckEdit<(&IsPlayer, &Vpeol2dPosition, &mut Vpeol2dRotatation)>,
mut knobs: YoleckKnobs,
) {
let Ok((_, Vpeol2dPosition(position), mut rotation)) = edit.single_mut() else {
return;
};
use std::f32::consts::PI;
ui.add(egui::Slider::new(&mut rotation.0, PI..=-PI).prefix("Angle: "));
let mut rotate_knob = knobs.knob("rotate");
let knob_position = position.extend(1.0) + Quat::from_rotation_z(rotation.0) * (50.0 * Vec3::Y);
rotate_knob.cmd.insert((
Sprite::from_color(css::PURPLE, Vec2::new(30.0, 30.0)),
Transform::from_translation(knob_position),
GlobalTransform::from(Transform::from_translation(knob_position)),
));
if let Some(rotate_to) = rotate_knob.get_passed_data::<Vec3>() {
rotation.0 = Vec2::Y.angle_to(rotate_to.truncate() - *position);
}
}
fn control_player(
mut player_query: Query<&mut Transform, With<IsPlayer>>,
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
) {
let mut velocity = Vec3::ZERO;
if input.pressed(KeyCode::ArrowUp) {
velocity += Vec3::Y;
}
if input.pressed(KeyCode::ArrowDown) {
velocity -= Vec3::Y;
}
if input.pressed(KeyCode::ArrowLeft) {
velocity -= Vec3::X;
}
if input.pressed(KeyCode::ArrowRight) {
velocity += Vec3::X;
}
velocity *= 400.0;
for mut player_transform in player_query.iter_mut() {
player_transform.translation += velocity * time.delta_secs();
}
}
// ============================================================================
// Fruit
// ============================================================================
#[derive(Component)]
struct IsFruit;
#[derive(
Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Component, YoleckComponent, Debug,
)]
struct FruitType {
index: usize,
}
fn duplicate_fruit(
mut ui: ResMut<YoleckUi>,
edit: YoleckEdit<(&YoleckBelongsToLevel, &FruitType, &Vpeol2dPosition)>,
mut writer: MessageWriter<YoleckDirective>,
) {
let Ok((belongs_to_level, fruit_type, Vpeol2dPosition(position))) = edit.single() else {
return;
};
if ui.button("Duplicate").clicked() {
writer.write(
YoleckDirective::spawn_entity(belongs_to_level.level, "Fruit", true)
.with(Vpeol2dPosition(*position - 100.0 * Vec2::Y))
.with(FruitType {
index: fruit_type.index,
})
.modify_exclusive_systems(|queue| queue.clear())
.into(),
);
}
}
fn edit_fruit_type(
mut ui: ResMut<YoleckUi>,
mut edit: YoleckEdit<(Entity, &mut FruitType, &Vpeol2dPosition)>,
assets: Res<GameAssets>,
mut knobs: YoleckKnobs,
) {
if edit.is_empty() {
return;
}
let (texture_id, rects) = &assets.fruits_sprite_sheet_egui;
let mut selected_fruit_types = vec![false; rects.len()];
for (entity, mut fruit_type, Vpeol2dPosition(position)) in edit.iter_matching_mut() {
selected_fruit_types[fruit_type.index] = true;
for index in 0..rects.len() {
if index != fruit_type.index {
let mut knob = knobs.knob((entity, "select", index));
let knob_position =
(*position + Vec2::new(-30.0 + index as f32 * 30.0, 50.0)).extend(1.0);
knob.cmd.insert((
Sprite {
image: assets.fruits_sprite_sheet_texture.clone(),
texture_atlas: Some(TextureAtlas {
layout: assets.fruits_sprite_sheet_layout.clone(),
index,
}),
custom_size: Some(Vec2::new(20.0, 20.0)),
..Default::default()
},
Transform::from_translation(knob_position),
GlobalTransform::from(Transform::from_translation(knob_position)),
));
if knob.get_passed_data::<YoleckKnobClick>().is_some() {
fruit_type.index = index;
}
}
}
}
if edit.has_nonmatching() {
return;
}
let selected_fruit_types = selected_fruit_types;
let are_multile_types_selected = 1 < selected_fruit_types
.iter()
.filter(|is_selected| **is_selected)
.count();
ui.horizontal(|ui| {
for (index, rect) in rects.iter().enumerate() {
if ui
.add_enabled(
are_multile_types_selected || !selected_fruit_types[index],
egui::Button::image(
egui::Image::new(egui::load::SizedTexture {
id: *texture_id,
size: egui::Vec2::new(25.0, 25.0),
})
.uv(*rect),
)
.selected(selected_fruit_types[index]),
)
.clicked()
{
for (_, mut fruit_type, _) in edit.iter_matching_mut() {
fruit_type.index = index;
}
}
}
});
}
fn populate_fruit(
mut populate: YoleckPopulate<&FruitType>,
assets: Res<GameAssets>,
marking: YoleckMarking,
) {
populate.populate(|_ctx, mut cmd, fruit| {
marking.despawn_marked(&mut cmd);
cmd.insert((
Visibility::default(),
VpeolWillContainClickableChildren,
IsFruit,
));
cmd.with_children(|commands| {
let mut child = commands.spawn(marking.marker());
child.insert((Sprite {
image: assets.fruits_sprite_sheet_texture.clone(),
texture_atlas: Some(TextureAtlas {
layout: assets.fruits_sprite_sheet_layout.clone(),
index: fruit.index,
}),
custom_size: Some(Vec2::new(100.0, 100.0)),
..Default::default()
},));
});
});
}
fn eat_fruits(
player_query: Query<&Transform, With<IsPlayer>>,
fruits_query: Query<(Entity, &Transform), With<IsFruit>>,
mut commands: Commands,
) {
for player_transform in player_query.iter() {
for (fruit_entity, fruit_transform) in fruits_query.iter() {
if player_transform
.translation
.distance_squared(fruit_transform.translation)
< 100.0f32.powi(2)
{
commands.entity(fruit_entity).despawn();
}
}
}
}
// ============================================================================
// FloatingText
// ============================================================================
#[derive(
Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent, YoleckAutoEdit,
)]
pub struct TextContent {
#[yoleck(multiline)]
text: String,
}
#[derive(
Default,
Clone,
PartialEq,
Serialize,
Deserialize,
Component,
YoleckComponent,
YoleckAutoEdit,
Debug,
)]
struct TextLaserPointer {
#[yoleck(entity_ref = "Fruit")]
target: YoleckEntityRef,
}
fn populate_text(mut populate: YoleckPopulate<&TextContent>, assets: Res<GameAssets>) {
populate.populate(|_ctx, mut cmd, content| {
cmd.insert((
Text2d(content.text.clone()),
TextFont {
font: assets.font.clone(),
font_size: 72.0,
..Default::default()
},
));
});
}
// ============================================================================
// Triangle
// ============================================================================
#[derive(Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
pub struct TriangleVertices {
vertices: [Vec2; 3],
}
impl Default for TriangleVertices {
fn default() -> Self {
Self {
vertices: [
Vec2::new(-50.0, -50.0),
Vec2::new(50.0, -50.0),
Vec2::new(50.0, 50.0),
],
}
}
}
fn edit_triangle(
mut edit: YoleckEdit<(&mut TriangleVertices, &GlobalTransform)>,
mut knobs: YoleckKnobs,
) {
let Ok((mut triangle, triangle_transform)) = edit.single_mut() else {
return;
};
for (index, vertex) in triangle.vertices.iter_mut().enumerate() {
let mut knob = knobs.knob(("move-vertex", index));
if let Some(move_to) = knob.get_passed_data::<Vec3>() {
*vertex = triangle_transform
.to_matrix()
.inverse()
.transform_point3(*move_to)
.truncate();
}
let knob_position = triangle_transform.transform_point(vertex.extend(1.0));
knob.cmd.insert((
Sprite::from_color(css::RED, Vec2::new(15.0, 15.0)),
Transform::from_translation(knob_position),
GlobalTransform::from(Transform::from_translation(knob_position)),
));
}
}
fn populate_triangle(
mut populate: YoleckPopulate<(&TriangleVertices, Option<&Mesh2d>)>,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut material_assets: ResMut<Assets<ColorMaterial>>,
) {
populate.populate(|_ctx, mut cmd, (triangle, mesh2d)| {
let mesh = if let Some(Mesh2d(mesh_handle)) = mesh2d {
mesh_assets
.get_mut(mesh_handle)
.expect("mesh inserted by previous invocation of this system")
} else {
let mesh_handle = mesh_assets.add(Mesh::new(
PrimitiveTopology::TriangleList,
RenderAssetUsages::default(),
));
let mesh = mesh_assets.get_mut(&mesh_handle);
cmd.insert((
Mesh2d(mesh_handle),
MeshMaterial2d(material_assets.add(Color::from(css::GREEN))),
));
mesh.expect("mesh was just inserted")
};
mesh.insert_attribute(
Mesh::ATTRIBUTE_POSITION,
triangle
.vertices
.iter()
.map(|point| point.extend(0.0).to_array())
.collect::<Vec<_>>(),
);
let mut indices = Vec::new();
for i in 1..(triangle.vertices.len() - 1) {
let i = i as u32;
indices.extend([0, i, i + 1]);
}
mesh.insert_indices(Indices::U32(indices));
});
}
// ============================================================================
// LaserPointer (shared)
// ============================================================================
fn draw_laser_pointers(
query: Query<(&TextLaserPointer, &GlobalTransform)>,
targets_query: Query<&GlobalTransform>,
mut gizmos: Gizmos,
) {
for (laser_pointer, source_transform) in query.iter() {
if let Some(target_entity) = laser_pointer.target.entity()
&& let Ok(target_transform) = targets_query.get(target_entity)
{
gizmos.line(
source_transform.translation(),
target_transform.translation(),
css::GREEN,
);
}
}
}
================================================
FILE: examples/example3d.rs
================================================
use std::path::Path;
use bevy::prelude::*;
use bevy::{color::palettes::css, log::LogPlugin};
use bevy_egui::EguiPlugin;
use bevy_yoleck::prelude::*;
use bevy_yoleck::vpeol::prelude::*;
use serde::{Deserialize, Serialize};
fn main() {
let mut app = App::new();
app.add_plugins(DefaultPlugins.set(LogPlugin {
custom_layer: bevy_yoleck::console_layer_factory,
..default()
}));
let level = std::env::args().nth(1);
if let Some(level) = level {
app.add_plugins(EguiPlugin::default());
app.add_plugins(YoleckPluginForGame);
app.add_plugins(Vpeol3dPluginForGame);
app.add_systems(
Startup,
move |asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(
asset_server.load(Path::new("levels3d").join(&level)),
));
},
);
} else {
app.add_plugins(EguiPlugin::default());
app.add_plugins(YoleckPluginForEditor);
app.add_plugins(Vpeol3dPluginForEditor::topdown());
app.add_plugins(VpeolSelectionCuePlugin::default());
app.insert_resource(bevy_yoleck::YoleckEditorLevelsDirectoryPath(
Path::new(".").join("assets").join("levels3d"),
));
#[cfg(target_arch = "wasm32")]
app.add_systems(
Startup,
|asset_server: Res<AssetServer>, mut commands: Commands| {
commands.spawn(YoleckLoadLevel(asset_server.load("levels3d/example.yol")));
},
);
}
app.add_systems(Startup, (setup_camera, setup_arena));
app.add_yoleck_entity_type({
YoleckEntityType::new("Spaceship")
.with::<Vpeol3dPosition>()
.with::<SpaceshipSettings>()
.insert_on_init(|| IsSpaceship)
});
app.add_yoleck_auto_edit::<SpaceshipSettings>();
app.add_systems(YoleckSchedule::Populate, populate_spaceship);
app.add_yoleck_entity_type({
YoleckEntityType::new("Planet")
.with_uuid()
.with::<Vpeol3dPosition>()
.with::<Vpeol3dRotation>()
.with::<Vpeol3dScale>()
.insert_on_init(|| IsPlanet)
.insert_on_init_during_editor(|| VpeolDragPlane::XY)
});
app.add_systems(YoleckSchedule::Populate, populate_planet);
app.add_yoleck_entity_type({
YoleckEntityType::new("PlanetPointer")
.with::<Vpeol3dPosition>()
.with::<LaserPointer>()
.insert_on_init(|| SimpleSphere)
.insert_on_init_during_editor(|| Vpeol3dSnapToPlane {
normal: Dir3::Y,
offset: 2.0,
})
});
app.add_yoleck_auto_edit::<LaserPointer>();
app.add_systems(YoleckSchedule::Populate, populate_simple_sphere);
app.add_systems(Update, draw_laser_pointers);
app.add_systems(
Update,
(control_spaceship, hit_planets).run_if(in_state(YoleckEditorState::GameActive)),
);
app.run();
}
// ============================================================================
// Setup
// ============================================================================
fn setup_camera(mut commands: Commands) {
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 16.0, 40.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
VpeolCameraState::default(),
Vpeol3dCameraControl::topdown(),
));
commands.spawn((
DirectionalLight {
color: Color::WHITE,
illuminance: 50_000.0,
shadows_enabled: true,
..Default::default()
},
Transform::from_xyz(0.0, 100.0, 0.0).looking_to(-Vec3::Y, Vec3::Z),
));
}
fn setup_arena(
mut commands: Commands,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
) {
let mesh = mesh_assets.add(Mesh::from(
Plane3d {
normal: Dir3::Y,
half_size: Vec2::new(100.0, 100.0),
}
.mesh(),
));
let material = material_assets.add(Color::from(css::GRAY));
commands.spawn((
Mesh3d(mesh),
MeshMaterial3d(material),
Transform::from_xyz(0.0, -10.0, 0.0),
));
}
// ============================================================================
// Spaceship
// ============================================================================
#[derive(Component)]
struct IsSpaceship;
#[derive(Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent, YoleckAutoEdit)]
struct SpaceshipSettings {
#[yoleck(label = "Speed", range(0.5..=10.0))]
speed: f32,
#[yoleck(label = "Rotation Speed", range(0.5..=5.0))]
rotation_speed: f32,
#[yoleck(label = "Enabled")]
enabled: bool,
}
impl Default for SpaceshipSettings {
fn default() -> Self {
Self {
speed: 2.0,
rotation_speed: 2.0,
enabled: true,
}
}
}
fn populate_spaceship(
mut populate: YoleckPopulate<&SpaceshipSettings, With<IsSpaceship>>,
asset_server: Res<AssetServer>,
) {
populate.populate(|ctx, mut cmd, _settings| {
cmd.insert(VpeolWillContainClickableChildren);
if ctx.is_first_time() {
cmd.insert(SceneRoot(asset_server.load("models/spaceship.glb#Scene0")));
}
});
}
fn control_spaceship(
mut query: Query<(&mut Transform, &SpaceshipSettings), With<IsSpaceship>>,
time: Res<Time>,
input: Res<ButtonInput<KeyCode>>,
) {
let calc_axis = |neg: KeyCode, pos: KeyCode| match (input.pressed(neg), input.pressed(pos)) {
(true, true) | (false, false) => 0.0,
(true, false) => -1.0,
(false, true) => 1.0,
};
let pitch = calc_axis(KeyCode::ArrowUp, KeyCode::ArrowDown);
let roll = calc_axis(KeyCode::ArrowLeft, KeyCode::ArrowRight);
for (mut transform, settings) in query.iter_mut() {
if !settings.enabled {
continue;
}
let forward = transform.rotation.mul_vec3(-Vec3::Z);
let roll_quat =
Quat::from_scaled_axis(settings.rotation_speed * forward * time.delta_secs() * roll);
let pitch_axis = transform.rotation.mul_vec3(Vec3::X);
let pitch_quat = Quat::from_scaled_axis(
settings.rotation_speed * pitch_axis * time.delta_secs() * pitch,
);
transform.rotation = roll_quat * pitch_quat * transform.rotation;
transform.translation += settings.speed * forward * time.delta_secs();
}
}
// ============================================================================
// Planet
// ============================================================================
#[derive(Component)]
struct IsPlanet;
fn populate_planet(
mut populate: YoleckPopulate<(), With<IsPlanet>>,
asset_server: Res<AssetServer>,
) {
populate.populate(|ctx, mut cmd, ()| {
cmd.insert(VpeolWillContainClickableChildren);
if ctx.is_first_time() {
cmd.insert(SceneRoot(asset_server.load("models/planet.glb#Scene0")));
}
});
}
fn hit_planets(
spaceship_query: Query<&Transform, With<IsSpaceship>>,
planets_query: Query<(Entity, &Transform), With<IsPlanet>>,
mut commands: Commands,
) {
for spaceship_transform in spaceship_query.iter() {
for (planet_entity, planet_transform) in planets_query.iter() {
let planet_radius = planet_transform.scale.max_element();
let hit_distance = planet_radius + 1.0;
if spaceship_transform
.translation
.distance_squared(planet_transform.translation)
< hit_distance.powi(2)
{
commands.entity(planet_entity).despawn();
}
}
}
}
// ============================================================================
// LaserPointer (PlanetPointer)
// ============================================================================
#[derive(Component)]
struct SimpleSphere;
#[derive(
Default,
Clone,
PartialEq,
Serialize,
Deserialize,
Component,
YoleckComponent,
YoleckAutoEdit,
Debug,
)]
struct LaserPointer {
#[yoleck(entity_ref = "Planet")]
target: YoleckEntityRef,
}
fn populate_simple_sphere(
mut populate: YoleckPopulate<(), With<SimpleSphere>>,
mut mesh_assets: ResMut<Assets<Mesh>>,
mut mesh: Local<Option<Handle<Mesh>>>,
mut material_assets: ResMut<Assets<StandardMaterial>>,
mut material: Local<Option<Handle<StandardMaterial>>>,
) {
populate.populate(|ctx, mut cmd, ()| {
if ctx.is_first_time() {
let mesh = mesh
.get_or_insert_with(|| mesh_assets.add(Mesh::from(Sphere { radius: 1.0 })))
.clone();
let material = material
.get_or_insert_with(|| material_assets.add(Color::from(css::YELLOW)))
.clone();
cmd.insert((Mesh3d(mesh), MeshMaterial3d(material)));
}
});
}
fn draw_laser_pointers(
query: Query<(&LaserPointer, &GlobalTransform)>,
targets_query: Query<&GlobalTransform>,
mut gizmos: Gizmos,
) {
for (laser_pointer, source_transform) in query.iter() {
if let Some(target_entity) = laser_pointer.target.entity()
&& let Ok(target_transform) = targets_query.get(target_entity)
{
gizmos.line(
source_transform.translation(),
target_transform.translation(),
css::LIMEGREEN,
);
}
}
}
================================================
FILE: macros/Cargo.toml
================================================
[package]
name = "bevy-yoleck-macros"
description = "Macros for bevy-yoleck"
version = "0.10.0"
edition.workspace = true
authors.workspace = true
license.workspace = true
repository.workspace = true
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full", "extra-traits"] }
quote = "1"
proc-macro2 = "1"
================================================
FILE: macros/src/lib.rs
================================================
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Error, Field, Fields, LitStr, Token, Type};
#[proc_macro_derive(YoleckComponent)]
pub fn derive_yoleck_component(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as DeriveInput);
match impl_yoleck_component_derive(input) {
Ok(output) => output.into(),
Err(error) => error.to_compile_error().into(),
}
}
fn impl_yoleck_component_derive(input: DeriveInput) -> Result<TokenStream, Error> {
let name = input.ident;
let key = name.to_string();
let result = quote!(
impl YoleckComponent for #name {
const KEY: &'static str = #key;
}
);
Ok(result)
}
#[derive(Default, Debug)]
struct YoleckFieldAttrs {
range: Option<(f64, f64)>,
step: Option<f64>,
label: Option<String>,
tooltip: Option<String>,
readonly: bool,
hidden: bool,
multiline: bool,
color_picker: bool,
asset_extensions: Option<Vec<String>>,
entity_filter: Option<String>,
speed: Option<f64>,
}
fn parse_number(expr: &syn::Expr) -> syn::Result<f64> {
match expr {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(i),
..
}) => Ok(i.base10_parse::<f64>()?),
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Float(f),
..
}) => Ok(f.base10_parse::<f64>()?),
syn::Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(_),
expr: inner,
..
}) => Ok(-parse_number(inner)?),
_ => Err(syn::Error::new_spanned(expr, "Expected numeric literal")),
}
}
fn parse_field_attrs(field: &Field) -> Result<YoleckFieldAttrs, Error> {
let mut attrs = YoleckFieldAttrs::default();
for attr in &field.attrs {
if !attr.path().is_ident("yoleck") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("readonly") {
attrs.readonly = true;
return Ok(());
}
if meta.path.is_ident("hidden") {
attrs.hidden = true;
return Ok(());
}
if meta.path.is_ident("multiline") {
attrs.multiline = true;
return Ok(());
}
if meta.path.is_ident("color_picker") {
attrs.color_picker = true;
return Ok(());
}
if meta.path.is_ident("label") {
let value: syn::LitStr = meta.value()?.parse()?;
attrs.label = Some(value.value());
return Ok(());
}
if meta.path.is_ident("tooltip") {
let value: syn::LitStr = meta.value()?.parse()?;
attrs.tooltip = Some(value.value());
return Ok(());
}
if meta.path.is_ident("step") {
let value: syn::LitFloat = meta.value()?.parse()?;
attrs.step = Some(value.base10_parse()?);
return Ok(());
}
if meta.path.is_ident("speed") {
let value: syn::LitFloat = meta.value()?.parse()?;
attrs.speed = Some(value.base10_parse()?);
return Ok(());
}
if meta.path.is_ident("asset") {
let value: syn::LitStr = meta.value()?.parse()?;
attrs.asset_extensions = Some(
value
.value()
.split(',')
.map(|s| s.trim().to_string())
.collect(),
);
return Ok(());
}
if meta.path.is_ident("entity_ref") {
let value: syn::LitStr = meta.value()?.parse()?;
attrs.entity_filter = Some(value.value());
return Ok(());
}
if meta.path.is_ident("range") {
let content;
syn::parenthesized!(content in meta.input);
let expr: syn::Expr = content.parse()?;
match expr {
syn::Expr::Range(syn::ExprRange {
start: Some(start),
end: Some(end),
limits: syn::RangeLimits::Closed(_),
..
}) => {
let start_val = parse_number(&start)?;
let end_val = parse_number(&end)?;
attrs.range = Some((start_val, end_val));
return Ok(());
}
_ => {
return Err(syn::Error::new_spanned(
expr,
"Expected closed numeric range, e.g., `0.5..=10.0`",
));
}
}
}
Err(meta.error("unknown yoleck attribute"))
})?;
}
Ok(attrs)
}
fn get_type_name(ty: &Type) -> String {
match ty {
Type::Path(type_path) => type_path
.path
.segments
.last()
.map(|s| s.ident.to_string())
.unwrap_or_default(),
_ => String::new(),
}
}
fn quote_option<T, F>(opt: &Option<T>, f: F) -> TokenStream
where
F: FnOnce(&T) -> TokenStream,
{
match opt {
Some(value) => {
let inner = f(value);
quote! { Some(#inner) }
}
None => quote! { None },
}
}
fn generate_field_ui(field: &Field, attrs: &YoleckFieldAttrs) -> TokenStream {
let field_name = field.ident.as_ref().unwrap();
let field_name_str = attrs
.label
.clone()
.unwrap_or_else(|| field_name.to_string().replace('_', " "));
let range = quote_option(&attrs.range, |(min, max)| quote! { (#min, #max) });
let speed = quote_option(&attrs.speed, |s| quote! { #s });
let label_opt = quote_option(&attrs.label, |l| quote! { #l.to_string() });
let tooltip = quote_option(&attrs.tooltip, |t| quote! { #t.to_string() });
let entity_filter = quote_option(&attrs.entity_filter, |f| quote! { #f.to_string() });
let readonly = attrs.readonly;
let multiline = attrs.multiline;
quote! {
{
use bevy_yoleck::auto_edit::{YoleckAutoEdit, FieldAttrs};
let attrs = FieldAttrs {
label: #label_opt,
tooltip: #tooltip,
range: #range,
speed: #speed,
readonly: #readonly,
multiline: #multiline,
entity_filter: #entity_filter,
};
YoleckAutoEdit::auto_edit_with_label_and_attrs(
&mut value.#field_name,
ui,
#field_name_str,
&attrs,
);
}
}
}
#[proc_macro_derive(YoleckAutoEdit, attributes(yoleck))]
pub fn derive_yoleck_auto_edit(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as DeriveInput);
match impl_yoleck_auto_edit_derive(input) {
Ok(output) => output.into(),
Err(error) => error.to_compile_error().into(),
}
}
fn impl_yoleck_auto_edit_derive(input: DeriveInput) -> Result<TokenStream, Error> {
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let fields = if let Data::Struct(data) = &input.data {
if let Fields::Named(fields) = &data.fields {
&fields.named
} else {
return Err(Error::new_spanned(
&input,
"YoleckAutoEdit only supports structs with named fields",
));
}
} else {
return Err(Error::new_spanned(
&input,
"YoleckAutoEdit only supports structs",
));
};
let mut field_uis = Vec::new();
for field in fields {
let attrs = parse_field_attrs(field)?;
if attrs.hidden {
continue;
}
field_uis.push(generate_field_ui(field, &attrs));
}
let mut entity_ref_fields = Vec::new();
let mut entity_ref_field_names = Vec::new();
for field in fields {
if let Some(info) = parse_entity_ref_attrs(field)? {
entity_ref_fields.push(info);
entity_ref_field_names.push(
field
.ident
.as_ref()
.expect("fields are taken from a named struct variant"),
);
}
}
let fields_array: Vec<TokenStream> = entity_ref_fields
.iter()
.map(|info| {
let field_ident = &info.field_ident;
let field_ident_str = LitStr::new(&field_ident.to_string(), field_ident.span());
let filter = match &info.filter {
Some(f) => quote! { Some(#f) },
None => quote! { None },
};
quote! { (#field_ident_str, #filter) }
})
.collect();
let match_arms: Vec<TokenStream> = entity_ref_fields
.iter()
.map(|info| {
let field_ident = &info.field_ident;
let field_ident_str = LitStr::new(&field_ident.to_string(), field_ident.span());
quote! {
#field_ident_str => &mut self.#field_ident
}
})
.collect();
let fields_count = entity_ref_fields.len();
let get_entity_ref_mut_body = if entity_ref_fields.is_empty() {
quote! {
panic!("No entity ref fields in {}", stringify!(#name))
}
} else {
quote! {
match field_name {
#(#match_arms,)*
_ => panic!("Unknown entity ref field: {}", field_name),
}
}
};
let result = quote! {
impl #impl_generics bevy_yoleck::auto_edit::YoleckAutoEdit for #name #ty_generics #where_clause {
fn auto_edit(value: &mut Self, ui: &mut bevy_yoleck::egui::Ui) {
use bevy_yoleck::egui;
#(#field_uis)*
}
}
impl #impl_generics bevy_yoleck::entity_ref::YoleckEntityRefAccessor for #name #ty_generics #where_clause {
fn entity_ref_fields() -> &'static [(&'static str, Option<&'static str>)] {
static FIELDS: [(&'static str, Option<&'static str>); #fields_count] = [
#(#fields_array),*
];
&FIELDS
}
fn get_entity_ref_mut(&mut self, field_name: &str) -> &mut bevy_yoleck::entity_ref::YoleckEntityRef {
#get_entity_ref_mut_body
}
fn resolve_entity_refs(&mut self, registry: &bevy_yoleck::prelude::YoleckUuidRegistry) {
#(
let _ = self.#entity_ref_field_names.resolve(registry);
)*
}
}
};
Ok(result)
}
#[derive(Debug)]
struct EntityRefFieldInfo {
field_ident: syn::Ident,
filter: Option<String>,
}
fn parse_entity_ref_attrs(field: &Field) -> Result<Option<EntityRefFieldInfo>, Error> {
let type_name = get_type_name(&field.ty);
if type_name != "YoleckEntityRef" {
return Ok(None);
}
let field_ident = field
.ident
.as_ref()
.ok_or_else(|| Error::new_spanned(field, "Expected named field"))?
.clone();
let mut info = EntityRefFieldInfo {
field_ident,
filter: None,
};
for attr in &field.attrs {
if !attr.path().is_ident("yoleck") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("entity_ref") {
if meta.input.peek(Token![=]) {
let value: syn::LitStr = meta.value()?.parse()?;
info.filter = Some(value.value());
}
return Ok(());
}
Ok(())
})?;
}
Ok(Some(info))
}
================================================
FILE: run-retrospective-crate-version-tagging.sh
================================================
#!/bin/bash
(
retrospective-crate-version-tagging detect \
--crate-name bevy-yoleck \
--changelog-path CHANGELOG.md \
--tag-prefix v \
) | retrospective-crate-version-tagging create-releases
================================================
FILE: src/auto_edit.rs
================================================
use bevy::prelude::*;
use bevy_egui::egui;
use crate::YoleckInternalSchedule;
use crate::entity_ref::resolve_entity_refs;
use crate::entity_ref::validate_entity_ref_requirements_for;
use crate::entity_ref::YoleckEntityRef;
use crate::prelude::YoleckUuidRegistry;
use std::collections::HashMap;
/// Attributes that can be applied to fields for customizing their UI
#[derive(Default, Clone)]
pub struct FieldAttrs {
pub label: Option<String>,
pub tooltip: Option<String>,
pub range: Option<(f64, f64)>,
pub speed: Option<f64>,
pub readonly: bool,
pub multiline: bool,
pub entity_filter: Option<String>,
}
pub trait YoleckAutoEdit: Send + Sync + 'static {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui);
/// Auto-edit with field-level attributes (label, tooltip, range, etc.)
/// Default implementation wraps auto_edit with label and common decorations
fn auto_edit_with_label_and_attrs(
value: &mut Self,
ui: &mut egui::Ui,
label: &str,
attrs: &FieldAttrs,
) {
if attrs.readonly {
ui.add_enabled_ui(false, |ui| {
Self::auto_edit_field_impl(value, ui, label, attrs);
});
} else {
Self::auto_edit_field_impl(value, ui, label, attrs);
}
}
/// Internal implementation for field rendering with label
/// Types can override this to customize behavior based on attributes
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
ui.horizontal(|ui| {
ui.label(label);
let response = ui
.scope(|ui| {
Self::auto_edit(value, ui);
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
});
}
}
pub fn render_auto_edit_value<T: YoleckAutoEdit>(ui: &mut egui::Ui, value: &mut T) {
T::auto_edit(value, ui);
}
impl YoleckAutoEdit for f32 {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.add(egui::DragValue::new(value).speed(0.1));
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
ui.horizontal(|ui| {
ui.label(label);
let response = if let Some((min, max)) = attrs.range {
ui.add(egui::Slider::new(value, min as f32..=max as f32))
} else {
let speed = attrs.speed.unwrap_or(0.1) as f32;
ui.add(egui::DragValue::new(value).speed(speed))
};
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
});
}
}
impl YoleckAutoEdit for f64 {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.add(egui::DragValue::new(value).speed(0.1));
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
ui.horizontal(|ui| {
ui.label(label);
let response = if let Some((min, max)) = attrs.range {
ui.add(egui::Slider::new(value, min..=max))
} else {
let speed = attrs.speed.unwrap_or(0.1);
ui.add(egui::DragValue::new(value).speed(speed))
};
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
});
}
}
macro_rules! impl_auto_edit_for_integer {
($($ty:ty),*) => {
$(
impl YoleckAutoEdit for $ty {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.add(egui::DragValue::new(value).speed(1.0));
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
ui.horizontal(|ui| {
ui.label(label);
let response = if let Some((min, max)) = attrs.range {
ui.add(egui::Slider::new(value, min as $ty..=max as $ty))
} else {
let speed = attrs.speed.unwrap_or(1.0) as f32;
ui.add(egui::DragValue::new(value).speed(speed))
};
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
});
}
}
)*
};
}
impl_auto_edit_for_integer!(i32, i64, u32, u64, usize, isize);
impl YoleckAutoEdit for bool {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.checkbox(value, "");
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
ui.horizontal(|ui| {
let response = ui.checkbox(value, label);
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
});
}
}
impl YoleckAutoEdit for String {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.text_edit_singleline(value);
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
if attrs.multiline {
ui.label(label);
let response = ui.text_edit_multiline(value);
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
} else {
ui.horizontal(|ui| {
ui.label(label);
let response = ui.text_edit_singleline(value);
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
});
}
}
}
impl YoleckAutoEdit for Vec2 {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut value.x).prefix("x: ").speed(0.1));
ui.add(egui::DragValue::new(&mut value.y).prefix("y: ").speed(0.1));
});
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let speed = attrs.speed.unwrap_or(0.1) as f32;
let response = ui
.horizontal(|ui| {
ui.label(label);
ui.add(
egui::DragValue::new(&mut value.x)
.prefix("x: ")
.speed(speed),
);
ui.add(
egui::DragValue::new(&mut value.y)
.prefix("y: ")
.speed(speed),
);
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
}
}
impl YoleckAutoEdit for Vec3 {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut value.x).prefix("x: ").speed(0.1));
ui.add(egui::DragValue::new(&mut value.y).prefix("y: ").speed(0.1));
ui.add(egui::DragValue::new(&mut value.z).prefix("z: ").speed(0.1));
});
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let speed = attrs.speed.unwrap_or(0.1) as f32;
let response = ui
.horizontal(|ui| {
ui.label(label);
ui.add(
egui::DragValue::new(&mut value.x)
.prefix("x: ")
.speed(speed),
);
ui.add(
egui::DragValue::new(&mut value.y)
.prefix("y: ")
.speed(speed),
);
ui.add(
egui::DragValue::new(&mut value.z)
.prefix("z: ")
.speed(speed),
);
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
}
}
impl YoleckAutoEdit for Vec4 {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
ui.add(egui::DragValue::new(&mut value.x).prefix("x: ").speed(0.1));
ui.add(egui::DragValue::new(&mut value.y).prefix("y: ").speed(0.1));
ui.add(egui::DragValue::new(&mut value.z).prefix("z: ").speed(0.1));
ui.add(egui::DragValue::new(&mut value.w).prefix("w: ").speed(0.1));
});
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let speed = attrs.speed.unwrap_or(0.1) as f32;
let response = ui
.horizontal(|ui| {
ui.label(label);
ui.add(
egui::DragValue::new(&mut value.x)
.prefix("x: ")
.speed(speed),
);
ui.add(
egui::DragValue::new(&mut value.y)
.prefix("y: ")
.speed(speed),
);
ui.add(
egui::DragValue::new(&mut value.z)
.prefix("z: ")
.speed(speed),
);
ui.add(
egui::DragValue::new(&mut value.w)
.prefix("w: ")
.speed(speed),
);
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
}
}
impl YoleckAutoEdit for Quat {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
let (mut yaw, mut pitch, mut roll) = value.to_euler(EulerRot::YXZ);
yaw = yaw.to_degrees();
pitch = pitch.to_degrees();
roll = roll.to_degrees();
ui.horizontal(|ui| {
let mut changed = false;
changed |= ui
.add(
egui::DragValue::new(&mut yaw)
.prefix("yaw: ")
.speed(1.0)
.suffix("°"),
)
.changed();
changed |= ui
.add(
egui::DragValue::new(&mut pitch)
.prefix("pitch: ")
.speed(1.0)
.suffix("°"),
)
.changed();
changed |= ui
.add(
egui::DragValue::new(&mut roll)
.prefix("roll: ")
.speed(1.0)
.suffix("°"),
)
.changed();
if changed {
*value = Quat::from_euler(
EulerRot::YXZ,
yaw.to_radians(),
pitch.to_radians(),
roll.to_radians(),
);
}
});
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let speed = attrs.speed.unwrap_or(1.0) as f32;
let response = ui
.horizontal(|ui| {
ui.label(label);
let (mut yaw, mut pitch, mut roll) = value.to_euler(EulerRot::YXZ);
yaw = yaw.to_degrees();
pitch = pitch.to_degrees();
roll = roll.to_degrees();
let mut changed = false;
changed |= ui
.add(
egui::DragValue::new(&mut yaw)
.prefix("yaw: ")
.speed(speed)
.suffix("°"),
)
.changed();
changed |= ui
.add(
egui::DragValue::new(&mut pitch)
.prefix("pitch: ")
.speed(speed)
.suffix("°"),
)
.changed();
changed |= ui
.add(
egui::DragValue::new(&mut roll)
.prefix("roll: ")
.speed(speed)
.suffix("°"),
)
.changed();
if changed {
*value = Quat::from_euler(
EulerRot::YXZ,
yaw.to_radians(),
pitch.to_radians(),
roll.to_radians(),
);
}
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
}
}
impl YoleckAutoEdit for Color {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
let srgba = value.to_srgba();
let mut color_arr = [srgba.red, srgba.green, srgba.blue, srgba.alpha];
if ui
.color_edit_button_rgba_unmultiplied(&mut color_arr)
.changed()
{
*value = Color::srgba(color_arr[0], color_arr[1], color_arr[2], color_arr[3]);
}
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let response = ui
.horizontal(|ui| {
ui.label(label);
let srgba = value.to_srgba();
let mut color_arr = [srgba.red, srgba.green, srgba.blue, srgba.alpha];
if ui
.color_edit_button_rgba_unmultiplied(&mut color_arr)
.changed()
{
*value = Color::srgba(color_arr[0], color_arr[1], color_arr[2], color_arr[3]);
}
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
}
}
impl<T: YoleckAutoEdit + Default> YoleckAutoEdit for Option<T> {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
let mut has_value = value.is_some();
if ui.checkbox(&mut has_value, "").changed() {
if has_value {
*value = Some(T::default());
} else {
*value = None;
}
}
if let Some(inner) = value.as_mut() {
T::auto_edit(inner, ui);
}
});
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let response = ui
.horizontal(|ui| {
ui.label(label);
let mut has_value = value.is_some();
if ui.checkbox(&mut has_value, "").changed() {
if has_value {
*value = Some(T::default());
} else {
*value = None;
}
}
if let Some(inner) = value.as_mut() {
T::auto_edit(inner, ui);
}
})
.response;
if let Some(tooltip) = &attrs.tooltip {
response.on_hover_text(tooltip);
}
}
}
impl<T: YoleckAutoEdit + Default> YoleckAutoEdit for Vec<T> {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
let mut to_remove = None;
for (idx, item) in value.iter_mut().enumerate() {
ui.horizontal(|ui| {
ui.label(format!("[{}]", idx));
T::auto_edit(item, ui);
if ui.small_button("−").clicked() {
to_remove = Some(idx);
}
});
}
if let Some(idx) = to_remove {
value.remove(idx);
}
if ui.small_button("+").clicked() {
value.push(T::default());
}
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
let response = ui.collapsing(label, |ui| {
let mut to_remove = None;
for (idx, item) in value.iter_mut().enumerate() {
ui.horizontal(|ui| {
ui.label(format!("[{}]", idx));
T::auto_edit(item, ui);
if ui.small_button("−").clicked() {
to_remove = Some(idx);
}
});
}
if let Some(idx) = to_remove {
value.remove(idx);
}
if ui.small_button("+").clicked() {
value.push(T::default());
}
});
if let Some(tooltip) = &attrs.tooltip {
response.header_response.on_hover_text(tooltip);
}
}
}
impl<T: YoleckAutoEdit> YoleckAutoEdit for [T] {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
for (idx, item) in value.iter_mut().enumerate() {
ui.horizontal(|ui| {
ui.label(format!("[{}]", idx));
T::auto_edit(item, ui);
});
}
}
}
#[derive(Clone)]
struct EntityRefDisplayInfo {
pub type_name: String,
pub name: String,
}
impl YoleckAutoEdit for YoleckEntityRef {
fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
ui.horizontal(|ui| {
if let Some(uuid) = value.uuid() {
ui.label(uuid.to_string());
if ui.small_button("✕").clicked() {
value.clear();
}
} else {
ui.label("None");
}
});
}
fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &str, attrs: &FieldAttrs) {
// Get entity info map once for both display and drag&drop validation
let entity_info_map = ui.ctx().data(|data| {
data.get_temp::<HashMap<uuid::Uuid, EntityRefDisplayInfo>>(egui::Id::new(
"yoleck_entity_ref_display_info",
))
});
let response = ui
.horizontal(|ui| {
ui.label(label);
let display_text = if let Some(uuid) = value.uuid() {
if let Some(ref info_map) = entity_info_map {
if let Some(info) = info_map.get(&uuid) {
if info.name.is_empty() {
let uuid_str = uuid.to_string();
let uuid_short = &uuid_str[..uuid_str.len().min(8)];
format!("{} ({})", info.type_name, uuid_short)
} else {
format!("{} - {}", info.type_name, info.name)
}
} else {
uuid.to_string()
}
} else {
uuid.to_string()
}
} else {
"None".to_string()
};
ui.add(
egui::Button::new(
egui::RichText::new(display_text)
.text_style(ui.style().drag_value_text_style.clone()),
)
.wrap_mode(egui::TextWrapMode::Extend)
.min_size(ui.spacing().interact_size),
);
if value.is_some() && ui.small_button("✕").clicked() {
value.clear();
}
if let Some(tooltip) = &attrs.tooltip {
ui.label("ⓘ").on_hover_text(tooltip);
}
})
.response;
// Handle drag & drop
if let Some(dropped_uuid) = response.dnd_release_payload::<uuid::Uuid>() {
let dropped_uuid = *dropped_uuid;
let should_accept = if let Some(filter) = &attrs.entity_filter {
entity_info_map
.as_ref()
.and_then(|map| map.get(&dropped_uuid))
.is_none_or(|info| &info.type_name == filter)
} else {
true
};
if should_accept {
value.set(dropped_uuid);
}
}
}
}
use crate::YoleckExtForApp;
use crate::editing::{YoleckEdit, YoleckUi};
use crate::specs_registration::YoleckComponent;
use crate::entity_ref::YoleckEntityRefAccessor;
use bevy::ecs::component::Mutable;
use crate::YoleckManaged;
use crate::entity_uuid::YoleckEntityUuid;
pub fn auto_edit_system<T: YoleckComponent + YoleckAutoEdit + YoleckEntityRefAccessor>(
mut ui: ResMut<YoleckUi>,
mut edit: YoleckEdit<&mut T>,
entities_query: Query<(&YoleckEntityUuid, &YoleckManaged)>,
registry: Res<YoleckUuidRegistry>,
) {
let Ok(mut component) = edit.single_mut() else {
return;
};
// Populate entity display info in egui context only if component has entity ref fields
if !T::entity_ref_fields().is_empty() {
let entity_count = entities_query.iter().len();
let mut entity_info_map = HashMap::with_capacity(entity_count);
for (entity_uuid, managed) in entities_query.iter() {
entity_info_map.insert(
entity_uuid.get(),
EntityRefDisplayInfo {
type_name: managed.type_name.clone(),
name: managed.name.clone(),
},
);
}
ui.ctx().data_mut(|data| {
data.insert_temp(
egui::Id::new("yoleck_entity_ref_display_info"),
entity_info_map,
);
});
}
ui.group(|ui| {
ui.label(egui::RichText::new(T::KEY).strong());
ui.separator();
T::auto_edit(&mut component, ui);
});
component.resolve_entity_refs(registry.as_ref());
}
pub trait YoleckAutoEditExt {
fn add_yoleck_auto_edit<
T: Component<Mutability = Mutable>
+ YoleckComponent
+ YoleckAutoEdit
+ YoleckEntityRefAccessor,
>(
&mut self,
);
}
impl YoleckAutoEditExt for App {
fn add_yoleck_auto_edit<
T: Component<Mutability = Mutable>
+ YoleckComponent
+ YoleckAutoEdit
+ YoleckEntityRefAccessor,
>(
&mut self,
) {
self.add_yoleck_edit_system(auto_edit_system::<T>);
self.add_systems(
YoleckInternalSchedule::PostLoadResolutions,
resolve_entity_refs::<T>,
);
let construction_specs = self
.world_mut()
.get_resource::<crate::YoleckEntityConstructionSpecs>();
if let Some(specs) = construction_specs {
validate_entity_ref_requirements_for::<T>(specs);
}
}
}
================================================
FILE: src/console.rs
================================================
use bevy::log::BoxedLayer;
use bevy::log::tracing;
use bevy::log::tracing_subscriber;
use bevy::prelude::*;
use bevy_egui::egui;
use std::collections::VecDeque;
use std::sync::mpsc;
use crate::editor_panels::YoleckPanelUi;
/// Log level for console messages.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogLevel {
Debug,
Info,
Warn,
Error,
}
impl LogLevel {
pub fn color(&self) -> egui::Color32 {
match self {
LogLevel::Debug => egui::Color32::LIGHT_GRAY,
LogLevel::Info => egui::Color32::WHITE,
LogLevel::Warn => egui::Color32::from_rgb(255, 200, 0),
LogLevel::Error => egui::Color32::from_rgb(255, 100, 100),
}
}
pub fn label(&self) -> &str {
match self {
LogLevel::Debug => "DEBUG",
LogLevel::Info => "INFO",
LogLevel::Warn => "WARN",
LogLevel::Error => "ERROR",
}
}
}
/// A single log entry captured from the tracing system.
#[derive(Clone, Debug, Message)]
pub struct LogEntry {
pub level: LogLevel,
pub message: String,
pub target: String,
}
/// Non-send resource containing the receiver for captured log messages.
pub struct CapturedLogMessages(mpsc::Receiver<LogEntry>);
/// Resource storing the history of log messages displayed in the console.
#[derive(Resource)]
pub struct YoleckConsoleLogHistory {
pub logs: VecDeque<LogEntry>,
pub max_logs: usize,
}
impl YoleckConsoleLogHistory {
pub fn new(max_logs: usize) -> Self {
Self {
logs: VecDeque::with_capacity(max_logs),
max_logs,
}
}
pub fn add_log(&mut self, entry: LogEntry) {
if self.logs.len() >= self.max_logs {
self.logs.pop_front();
}
self.logs.push_back(entry);
}
pub fn clear(&mut self) {
self.logs.clear();
}
}
impl Default for YoleckConsoleLogHistory {
fn default() -> Self {
Self::new(1000)
}
}
/// Resource containing the current state of the console UI.
#[derive(Resource, Default)]
pub struct YoleckConsoleState {
pub log_filters: LogFilters,
}
/// Filters for controlling which log levels are displayed in the console.
#[derive(Resource)]
pub struct LogFilters {
pub show_debug: bool,
pub show_info: bool,
pub show_warn: bool,
pub show_error: bool,
}
impl Default for LogFilters {
fn default() -> Self {
Self {
show_debug: false,
show_info: true,
show_warn: true,
show_error: true,
}
}
}
impl LogFilters {
pub fn should_show(&self, level: LogLevel) -> bool {
match level {
LogLevel::Debug => self.show_debug,
LogLevel::Info => self.show_info,
LogLevel::Warn => self.show_warn,
LogLevel::Error => self.show_error,
}
}
}
/// Creates a console panel section for displaying log messages in the editor UI.
pub fn console_panel_section(
mut ui: ResMut<YoleckPanelUi>,
mut console_state: ResMut<YoleckConsoleState>,
mut log_history: ResMut<YoleckConsoleLogHistory>,
) -> Result {
ui.horizontal(|ui| {
ui.label("Filters:");
ui.checkbox(&mut console_state.log_filters.show_debug, "DEBUG");
ui.checkbox(&mut console_state.log_filters.show_info, "INFO");
ui.checkbox(&mut console_state.log_filters.show_warn, "WARN");
ui.checkbox(&mut console_state.log_filters.show_error, "ERROR");
ui.separator();
if ui.button("Clear").clicked() {
log_history.clear();
}
});
ui.separator();
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.stick_to_bottom(true)
.show(&mut ui, |ui| {
for log in log_history
.logs
.iter()
.filter(|log| console_state.log_filters.should_show(log.level))
{
ui.horizontal_wrapped(|ui| {
ui.colored_label(log.level.color(), format!("[{}]", log.level.label()));
ui.label(&log.message);
});
}
});
Ok(())
}
/// Tracing layer that captures log messages and sends them to the console.
pub struct YoleckConsoleLayer {
sender: mpsc::Sender<LogEntry>,
}
impl YoleckConsoleLayer {
pub fn new(sender: mpsc::Sender<LogEntry>) -> Self {
Self { sender }
}
}
impl<S> tracing_subscriber::Layer<S> for YoleckConsoleLayer
where
S: tracing::Subscriber,
{
fn on_event(
&self,
event: &tracing::Event<'_>,
_ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let metadata = event.metadata();
let level = match *metadata.level() {
tracing::Level::TRACE => return,
tracing::Level::DEBUG => LogLevel::Debug,
tracing::Level::INFO => LogLevel::Info,
tracing::Level::WARN => LogLevel::Warn,
tracing::Level::ERROR => LogLevel::Error,
};
let mut visitor = MessageVisitor::default();
event.record(&mut visitor);
if let Some(message) = visitor.message {
let _ = self.sender.send(LogEntry {
level,
message,
target: metadata.target().to_string(),
});
}
}
}
#[derive(Default)]
struct MessageVisitor {
message: Option<String>,
}
impl tracing::field::Visit for MessageVisitor {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" {
self.message = Some(format!("{:?}", value).trim_matches('"').to_string());
}
}
}
fn transfer_log_messages(
receiver: NonSend<CapturedLogMessages>,
mut message_writer: MessageWriter<LogEntry>,
) {
message_writer.write_batch(receiver.0.try_iter());
}
fn store_log_messages(
mut log_reader: MessageReader<LogEntry>,
log_history: Option<ResMut<YoleckConsoleLogHistory>>,
) {
let Some(mut log_history) = log_history else {
return;
};
for log in log_reader.read() {
log_history.add_log(log.clone());
}
}
/// Factory function that creates and configures the console logging layer.
///
/// This function should be used with Bevy's `LogPlugin` to capture log messages
/// and display them in the Yoleck editor console.
///
/// # Example
///
/// ```no_run
/// # use bevy::{prelude::*, log::LogPlugin};
/// # use bevy_yoleck::console_layer_factory;
///
/// fn main() {
/// App::new()
/// .add_plugins(DefaultPlugins.set(LogPlugin {
/// custom_layer: console_layer_factory,
/// ..default()
/// }))
/// .run();
/// }
/// ```
pub fn console_layer_factory(app: &mut App) -> Option<BoxedLayer> {
let (sender, receiver) = mpsc::channel();
let layer = YoleckConsoleLayer::new(sender);
let resource = CapturedLogMessages(receiver);
app.insert_non_send_resource(resource);
app.add_message::<LogEntry>();
app.add_systems(Update, (transfer_log_messages, store_log_messages).chain());
Some(Box::new(layer))
}
================================================
FILE: src/editing.rs
================================================
use std::ops::{Deref, DerefMut};
use bevy::ecs::query::{QueryData, QueryFilter, QueryIter, QuerySingleError};
use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
use bevy_egui::egui;
/// Marks which entities are currently being edited in the level editor.
#[derive(Component)]
pub struct YoleckEditMarker;
/// Wrapper for writing queries in edit systems.
///
/// To future-proof for the multi-entity editing feature, use this instead of
/// regular queries with `With<YoleckEditMarker>`.
///
/// The methods of `YoleckEdit` that have the same name as methods of a regular Bevy `Query`
/// delegate to them, but if there are edited entities that do not fit the query they will act as
/// if they found no match.
#[derive(SystemParam)]
pub struct YoleckEdit<'w, 's, Q: 'static + QueryData, F: 'static + QueryFilter = ()> {
query: Query<'w, 's, Q, (With<YoleckEditMarker>, F)>,
verification_query: Query<'w, 's, (), With<YoleckEditMarker>>,
}
impl<'s, Q: 'static + QueryData, F: 'static + QueryFilter> YoleckEdit<'_, 's, Q, F> {
pub fn single(
&self,
) -> Result<<<Q as QueryData>::ReadOnly as QueryData>::Item<'_, 's>, QuerySingleError> {
let single = self.query.single()?;
// This will return an error if multiple entities are selected (but only one fits F and Q)
self.verification_query.single()?;
Ok(single)
}
pub fn single_mut(&mut self) -> Result<<Q as QueryData>::Item<'_, 's>, QuerySingleError> {
let single = self.query.single_mut()?;
// This will return an error if multiple entities are selected (but only one fits F and Q)
self.verification_query.single()?;
Ok(single)
}
pub fn is_empty(&self) -> bool {
self.query.is_empty()
}
/// Check if some non-matching entities are selected for editing.
///
/// Use this, together with [`is_empty`](Self::is_empty) for systems that can edit multiple
/// entities but want to not show their UI when some irrelevant entities are selected as well.
pub fn has_nonmatching(&self) -> bool {
// Note - cannot use len for query.iter() because then `F` would be limited to archetype
// filters only.
self.query.iter().count() != self.verification_query.iter().len()
}
/// Iterate over all the matching entities, _even_ if some selected entities do not match.
///
/// If both matching and non-matching entities are selected, this will iterate over the
/// matching entities only. If it is not desired to iterate at all in such cases,
/// check [`has_nonmatching`](Self::has_nonmatching) must be checked manually.
pub fn iter_matching(
&mut self,
) -> QueryIter<'_, '_, <Q as QueryData>::ReadOnly, (bevy::prelude::With<YoleckEditMarker>, F)>
{
self.query.iter()
}
/// Iterate mutably over all the matching entities, _even_ if some selected entities do not match.
///
/// If both matching and non-matching entities are selected, this will iterate over the
/// matching entities only. If it is not desired to iterate at all in such cases,
/// check [`has_nonmatching`](Self::has_nonmatching) must be checked manually.
pub fn iter_matching_mut(&mut self) -> QueryIter<'_, '_, Q, (With<YoleckEditMarker>, F)> {
self.query.iter_mut()
}
}
/// An handle for the egui UI frame used in editing systems.
#[derive(Resource)]
pub struct YoleckUi(pub egui::Ui);
impl Deref for YoleckUi {
type Target = egui::Ui;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for YoleckUi {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
================================================
FILE: src/editor.rs
================================================
use std::any::TypeId;
use std::borrow::Cow;
use std::sync::Arc;
use bevy::ecs::system::SystemState;
use bevy::platform::collections::{HashMap, HashSet};
use bevy::prelude::*;
use bevy::state::state::FreelyMutableState;
use bevy_egui::egui;
use crate::editor_panels::YoleckPanelUi;
use crate::entity_management::{YoleckEntryHeader, YoleckRawEntry};
use crate::entity_uuid::YoleckEntityUuid;
use crate::exclusive_systems::{
YoleckActiveExclusiveSystem, YoleckEntityCreationExclusiveSystems,
YoleckExclusiveSystemDirective, YoleckExclusiveSystemsQueue,
};
use crate::knobs::YoleckKnobsCache;
use crate::prelude::{YoleckComponent, YoleckUi};
#[cfg(feature = "vpeol")]
use crate::vpeol;
use crate::{
BoxedArc, YoleckBelongsToLevel, YoleckEditMarker, YoleckEditSystems,
YoleckEntityConstructionSpecs, YoleckInternalSchedule, YoleckManaged, YoleckState,
};
/// Whether or not the Yoleck editor is active.
#[derive(States, Default, Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum YoleckEditorState {
/// Editor mode. The editor is active and can be used to edit entities.
#[default]
EditorActive,
/// Game mode. Either the actual game or playtest from the editor mode.
GameActive,
}
/// Sync the game's state back and forth when the level editor enters and exits playtest mode.
///
/// Add this as a plugin. When using it, there is no need to initialize the state with `add_state`
/// because `YoleckSyncWithEditorState` will initialize it and set its initial value to
/// `when_editor`. This means that the state's default value should be it's initial value for
/// non-editor mode (which is not necessarily `when_game`, because the game may start in a menu
/// state or a loading state)
///
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_yoleck::prelude::*;
/// # use bevy_yoleck::bevy_egui::EguiPlugin;
/// #[derive(States, Default, Debug, Clone, PartialEq, Eq, Hash)]
/// enum GameState {
/// #[default]
/// Loading,
/// Game,
/// Editor,
/// }
///
/// # let mut app = App::new();
/// # let executable_started_in_editor_mode = true;
/// if executable_started_in_editor_mode {
/// // These two plugins are needed for editor mode:
/// app.add_plugins(EguiPlugin::default());
/// app.add_plugins(YoleckPluginForEditor);
/// app.add_plugins(YoleckSyncWithEditorState {
/// when_editor: GameState::Editor,
/// when_game: GameState::Game,
/// });
/// } else {
/// // This plugin is needed for game mode:
/// app.add_plugins(YoleckPluginForGame);
///
/// app.init_state::<GameState>();
/// }
pub struct YoleckSyncWithEditorState<T>
where
T: 'static
+ States
+ FreelyMutableState
+ Sync
+ Send
+ std::fmt::Debug
+ Clone
+ std::cmp::Eq
+ std::hash::Hash,
{
pub when_editor: T,
pub when_game: T,
}
impl<T> Plugin for YoleckSyncWithEditorState<T>
where
T: 'static
+ States
+ FreelyMutableState
+ Sync
+ Send
+ std::fmt::Debug
+ Clone
+ std::cmp::Eq
+ std::hash::Hash,
{
fn build(&self, app: &mut App) {
app.insert_state(self.when_editor.clone());
let when_editor = self.when_editor.clone();
let when_game = self.when_game.clone();
app.add_systems(
Update,
move |editor_state: Res<State<YoleckEditorState>>,
mut game_state: ResMut<NextState<T>>| {
game_state.set(match editor_state.get() {
YoleckEditorState::EditorActive => when_editor.clone(),
YoleckEditorState::GameActive => when_game.clone(),
});
},
);
}
}
/// Events emitted by the Yoleck editor.
///
/// Modules that provide editing overlays over the viewport (like [vpeol](crate::vpeol)) can
/// use these events to update their status to match with the editor.
#[derive(Debug, Message)]
pub enum YoleckEditorEvent {
EntitySelected(Entity),
EntityDeselected(Entity),
EditedEntityPopulated(Entity),
}
enum YoleckDirectiveInner {
SetSelected(Option<Entity>),
ChangeSelectedStatus {
entity: Entity,
force_to: Option<bool>,
},
PassToEntity(Entity, TypeId, BoxedArc),
SpawnEntity {
level: Entity,
type_name: String,
data: serde_json::Map<String, serde_json::Value>,
select_created_entity: bool,
#[allow(clippy::type_complexity)]
modify_exclusive_systems:
Option<Box<dyn Sync + Send + Fn(&mut YoleckExclusiveSystemsQueue)>>,
},
}
/// Event that can be sent to control Yoleck's editor.
#[derive(Message)]
pub struct YoleckDirective(YoleckDirectiveInner);
impl YoleckDirective {
/// Pass data from an external system (usually a [ViewPort Editing OverLay](crate::vpeol)) to an entity.
///
/// This data can be received using the [`YoleckPassedData`] resource. If the data is
/// passed to a knob, it can also be received using the knob handle's
/// [`get_passed_data`](crate::knobs::YoleckKnobHandle::get_passed_data) method.
pub fn pass_to_entity<T: 'static + Send + Sync>(entity: Entity, data: T) -> Self {
Self(YoleckDirectiveInner::PassToEntity(
entity,
TypeId::of::<T>(),
Arc::new(data),
))
}
/// Set the entity selected in the Yoleck editor.
pub fn set_selected(entity: Option<Entity>) -> Self {
Self(YoleckDirectiveInner::SetSelected(entity))
}
/// Set the entity selected in the Yoleck editor.
pub fn toggle_selected(entity: Entity) -> Self {
Self(YoleckDirectiveInner::ChangeSelectedStatus {
entity,
force_to: None,
})
}
/// Spawn a new entity with pre-populated data.
///
/// ```no_run
/// # use serde::{Deserialize, Serialize};
/// # use bevy::prelude::*;
/// # use bevy_yoleck::prelude::*;
/// # use bevy_yoleck::YoleckDirective;
/// # use bevy_yoleck::vpeol_2d::Vpeol2dPosition;
/// # #[derive(Default, Clone, PartialEq, Serialize, Deserialize, Component, YoleckComponent)]
/// # struct Example;
/// fn duplicate_example(
/// mut ui: ResMut<YoleckUi>,
/// mut edit: YoleckEdit<(&YoleckBelongsToLevel, &Vpeol2dPosition), With<Example>>,
/// mut writer: MessageWriter<YoleckDirective>,
/// ) {
/// let Ok((belongs_to_level, position)) = edit.single() else { return };
/// if ui.button("Duplicate").clicked() {
/// writer.write(
/// YoleckDirective::spawn_entity(
/// belongs_to_level.level,
/// "Example",
/// // Automatically select the newly created entity:
/// true,
/// )
/// // Create the new example entity 100 units below the current one:
/// .with(Vpeol2dPosition(position.0 - 100.0 * Vec2::Y))
/// .into(),
/// );
/// }
/// }
/// ```
pub fn spawn_entity(
level: Entity,
type_name: impl ToString,
select_created_entity: bool,
) -> SpawnEntityBuilder {
SpawnEntityBuilder {
level,
type_name: type_name.to_string(),
select_created_entity,
data: Default::default(),
modify_exclusive_systems: None,
}
}
}
pub struct SpawnEntityBuilder {
level: Entity,
type_name: String,
select_created_entity: bool,
data: HashMap<Cow<'static, str>, serde_json::Value>,
#[allow(clippy::type_complexity)]
modify_exclusive_systems: Option<Box<dyn Sync + Send + Fn(&mut YoleckExclusiveSystemsQueue)>>,
}
impl SpawnEntityBuilder {
/// Override a component of the spawned entity.
pub fn with<T: YoleckComponent>(self, component: T) -> Self {
self.with_raw(
T::KEY,
serde_json::to_value(component).expect("should always work"),
)
}
pub fn with_raw(
mut self,
component_name: impl Into<Cow<'static, str>>,
component_data: serde_json::Value,
) -> Self {
self.data.insert(component_name.into(), component_data);
self
}
pub fn extend(
mut self,
components: impl Iterator<Item = (impl Into<Cow<'static, str>>, serde_json::Value)>,
) -> Self {
for (component_name, component_data) in components.into_iter() {
self = self.with_raw(component_name, component_data);
}
self
}
/// Change the exclusive systems that will be running the entity is spawned.
pub fn modify_exclusive_systems(
mut self,
dlg: impl 'static + Sync + Send + Fn(&mut YoleckExclusiveSystemsQueue),
) -> Self {
self.modify_exclusive_systems = Some(Box::new(dlg));
self
}
}
impl From<SpawnEntityBuilder> for YoleckDirective {
fn from(value: SpawnEntityBuilder) -> Self {
YoleckDirective(YoleckDirectiveInner::SpawnEntity {
level: value.level,
type_name: value.type_name,
data: value
.data
.into_iter()
.map(|(k, v)| (k.into_owned(), v))
.collect(),
select_created_entity: value.select_created_entity,
modify_exclusive_systems: value.modify_exclusive_systems,
})
}
}
#[derive(Resource)]
pub struct YoleckPassedData(pub(crate) HashMap<Entity, HashMap<TypeId, BoxedArc>>);
impl YoleckPassedData {
/// Get data sent to an entity from external systems (usually from (usually a [ViewPort Editing
/// OverLay](crate::vpeol))
///
/// The data is sent using [a directive event](crate::YoleckDirective::pass_to_entity).
///
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_yoleck::prelude::*;;
/// # #[derive(Component)]
/// # struct Example {
/// # message: String,
/// # }
/// fn edit_example(
/// mut edit: YoleckEdit<(Entity, &mut Example)>,
/// passed_data: Res<YoleckPassedData>,
/// ) {
/// let Ok((entity, mut example)) = edit.single_mut() else { return };
/// if let Some(message) = passed_data.get::<String>(entity) {
/// example.message = message.clone();
/// }
/// }
/// ```
pub fn get<T: 'static>(&self, entity: Entity) -> Option<&T> {
Some(
self.0
.get(&entity)?
.get(&TypeId::of::<T>())?
.downcast_ref()
.expect("Passed data TypeId must be correct"),
)
}
}
fn format_caption(entity: Entity, yoleck_managed: &YoleckManaged) -> String {
if yoleck_managed.name.is_empty() {
format!("{} {:?}", yoleck_managed.type_name, entity)
} else {
format!(
"{} ({} {:?})",
yoleck_managed.name, yoleck_managed.type_name, entity
)
}
}
/// The UI part for creating new entities. See [`YoleckEditorLeftPanelSections`](crate::YoleckEditorLeftPanelSections).
pub fn new_entity_section(
mut ui: ResMut<YoleckPanelUi>,
construction_specs: Res<YoleckEntityConstructionSpecs>,
yoleck: Res<YoleckState>,
editor_state: Res<State<YoleckEditorState>>,
mut writer: MessageWriter<YoleckDirective>,
active_exclusive_system: Option<Res<YoleckActiveExclusiveSystem>>,
) -> Result {
if active_exclusive_system.is_some() {
return Ok(());
}
if !matches!(editor_state.get(), YoleckEditorState::EditorActive) {
return Ok(());
}
let button_response = ui.button("Add New Entity");
egui::Popup::menu(&button_response).show(|ui| {
for entity_type in construction_specs.entity_types.iter() {
if ui.button(&entity_type.name).clicked() {
writer.write(YoleckDirective(YoleckDirectiveInner::SpawnEntity {
level: yoleck.level_being_edited,
type_name: entity_type.name.clone(),
data: Default::default(),
select_created_entity: true,
modify_exclusive_systems: None,
}));
}
}
});
Ok(())
}
/// The UI part for selecting entities. See [`YoleckEditorLeftPanelSections`](crate::YoleckEditorLeftPanelSections).
#[allow(clippy::too_many_arguments)]
pub fn entity_selection_section(
mut ui: ResMut<YoleckPanelUi>,
mut filter_custom_name: Local<String>,
mut filter_types: Local<HashSet<String>>,
construction_specs: Res<YoleckEntityConstructionSpecs>,
yoleck_managed_query: Query<(
Entity,
&YoleckManaged,
Option<&YoleckEditMarker>,
Option<&YoleckEntityUuid>,
)>,
editor_state: Res<State<YoleckEditorState>>,
mut writer: MessageWriter<YoleckDirective>,
active_exclusive_system: Option<Res<YoleckActiveExclusiveSystem>>,
#[cfg(feature = "vpeol")] vpeol_camera_state_query: Query<&vpeol::VpeolCameraState>,
) -> Result {
if active_exclusive_system.is_some() {
return Ok(());
}
if !matches!(editor_state.get(), YoleckEditorState::EditorActive) {
return Ok(());
}
egui::CollapsingHeader::new("Filter").show(ui.as_mut(), |ui| {
ui.horizontal(|ui| {
ui.label("By Name:");
ui.text_edit_singleline(&mut *filter_custom_name);
});
for entity_type in construction_specs.entity_types.iter() {
let mut should_show = filter_types.contains(&entity_type.name);
if ui.checkbox(&mut should_show, &entity_type.name).changed() {
if should_show {
filter_types.insert(entity_type.name.clone());
} else {
filter_types.remove(&entity_type.name);
}
}
}
});
#[cfg(not(feature = "vpeol"))]
let entities_under_cursor: HashSet<Entity> = Default::default();
#[cfg(feature = "vpeol")]
let entities_under_cursor: HashSet<Entity> = vpeol_camera_state_query
.iter()
.filter_map(|camera_state| Some(camera_state.entity_under_cursor.as_ref()?.0))
.collect();
for (entity, yoleck_managed, edit_marker, entity_uuid) in yoleck_managed_query.iter() {
if !filter_types.is_empty() && !filter_types.contains(&yoleck_managed.type_name) {
continue;
}
if !yoleck_managed.name.contains(filter_custom_name.as_str()) {
continue;
}
let is_selected = edit_marker.is_some();
let caption = format_caption(entity, yoleck_managed);
let mut potentially_highlighted_caption = egui::RichText::new(&caption);
if entities_under_cursor.contains(&entity) {
potentially_highlighted_caption =
potentially_highlighted_caption.background_color(egui::Color32::DARK_RED);
}
if let Some(entity_uuid) = entity_uuid {
let uuid = entity_uuid.get();
let sense = egui::Sense::click_and_drag();
let response = ui
.selectable_label(is_selected, potentially_highlighted_caption)
.interact(sense);
if response.drag_started() {
egui::DragAndDrop::set_payload(ui.ctx(), uuid);
} else if response.clicked() {
if ui.input(|input| input.modifiers.shift) {
writer.write(YoleckDirective::toggle_selected(entity));
} else if is_selected {
writer.write(YoleckDirective::set_selected(None));
} else {
writer.write(YoleckDirective::set_selected(Some(entity)));
}
}
if response.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
if let Some(pointer_pos) = ui.ctx().pointer_interact_pos() {
egui::Area::new(egui::Id::new("dragged_entity_preview"))
.fixed_pos(pointer_pos + egui::vec2(10.0, 10.0))
.order(egui::Order::Tooltip)
.show(ui.ctx(), |ui| {
egui::Frame::popup(ui.style()).show(ui, |ui| {
ui.label(caption);
});
});
}
}
} else if ui
.selectable_label(is_selected, potentially_highlighted_caption)
.clicked()
{
if ui.input(|input| input.modifiers.shift) {
writer.write(YoleckDirective::toggle_selected(entity));
} else if is_selected {
writer.write(YoleckDirective::set_selected(None));
} else {
writer.write(YoleckDirective::set_selected(Some(entity)));
}
}
}
Ok(())
}
/// The UI part for editing entities. See [`YoleckEditorLeftPanelSections`](crate::YoleckEditorLeftPanelSections).
#[allow(clippy::type_complexity)]
pub fn entity_editing_section(
world: &mut World,
mut previously_edited_entity: Local<Option<Entity>>,
mut new_entity_created_this_frame: Local<bool>,
mut system_state: Local<
Option<
SystemState<(
ResMut<YoleckState>,
Query<(Entity, &mut YoleckManaged), With<YoleckEditMarker>>,
Query<Entity, With<YoleckEditMarker>>,
MessageReader<YoleckDirective>,
Commands,
Res<State<YoleckEditorState>>,
MessageWriter<YoleckEditorEvent>,
ResMut<YoleckKnobsCache>,
Option<Res<YoleckActiveExclusiveSystem>>,
ResMut<YoleckExclusiveSystemsQueue>,
Res<YoleckEntityCreationExclusiveSystems>,
)>,
>,
>,
) -> Result {
let system_state = system_state.get_or_insert_with(|| SystemState::new(world));
world.resource_scope(|world, mut ui: Mut<YoleckPanelUi>| {
let ui = &mut **ui;
let mut passed_data = YoleckPassedData(Default::default());
{
let (
mut yoleck,
mut yoleck_managed_query,
yoleck_edited_query,
mut directives_reader,
mut commands,
editor_state,
mut writer,
mut knobs_cache,
active_exclusive_system,
mut exclusive_systems_queue,
entity_creation_exclusive_systems,
) = system_state.get_mut(world);
if !matches!(editor_state.get(), YoleckEditorState::EditorActive) {
return Ok(());
}
let mut data_passed_to_entities: HashMap<Entity, HashMap<TypeId, BoxedArc>> =
Default::default();
for directive in directives_reader.read() {
match &directive.0 {
YoleckDirectiveInner::PassToEntity(entity, type_id, data) => {
if false {
data_passed_to_entities
.entry(*entity)
.or_default()
.insert(*type_id, data.clone());
}
passed_data
.0
.entry(*entity)
.or_default()
.insert(*type_id, data.clone());
}
YoleckDirectiveInner::SetSelected(entity) => {
if active_exclusive_system.is_some() {
// TODO: pass the selection command to the exclusive system?
continue;
}
if let Some(entity) = entity {
let mut already_selected = false;
for entity_to_deselect in yoleck_edited_query.iter() {
if entity_to_deselect == *entity {
already_selected = true;
} else {
commands
.entity(entity_to_deselect)
.remove::<YoleckEditMarker>();
writer.write(YoleckEditorEvent::EntityDeselected(
entity_to_deselect,
));
}
}
if !already_selected {
commands.entity(*entity).insert(YoleckEditMarker);
writer.write(YoleckEditorEvent::EntitySelected(*entity));
}
} else {
for entity_to_deselect in yoleck_edited_query.iter() {
commands
.entity(entity_to_deselect)
.remove::<YoleckEditMarker>();
writer
.write(YoleckEditorEvent::EntityDeselected(entity_to_deselect));
}
}
}
YoleckDirectiveInner::ChangeSelectedStatus { entity, force_to } => {
if active_exclusive_system.is_some() {
// TODO: pass the selection command to the exclusive system?
continue;
}
match (force_to, yoleck_edited_query.contains(*entity)) {
(Some(true), true) | (Some(false), false) => {
// Nothing to do
}
(None, false) | (Some(true), false) => {
// Add to selection
commands.entity(*entity).insert(YoleckEditMarker);
writer.write(YoleckEditorEvent::EntitySelected(*entity));
}
(None, true) | (Some(false), true) => {
// Remove from selection
commands.entity(*entity).remove::<YoleckEditMarker>();
writer.write(YoleckEditorEvent::EntityDeselected(*entity));
}
}
}
YoleckDirectiveInner::SpawnEntity {
level,
type_name,
data,
select_created_entity,
modify_exclusive_systems: override_exclusive_systems,
} => {
if active_exclusive_system.is_some() {
continue;
}
let mut cmd = commands.spawn((
YoleckRawEntry {
header: YoleckEntryHeader {
type_name: type_name.clone(),
name: "".to_owned(),
uuid: None,
},
data: data.clone(),
},
YoleckBelongsToLevel { level: *level },
));
if *select_created_entity {
writer.write(YoleckEditorEvent::EntitySelected(cmd.id()));
cmd.insert(YoleckEditMarker);
for entity_to_deselect in yoleck_edited_query.iter() {
commands
.entity(entity_to_deselect)
.remove::<YoleckEditMarker>();
writer
.write(YoleckEditorEvent::EntityDeselected(entity_to_deselect));
}
*exclusive_systems_queue =
entity_creation_exclusive_systems.create_queue();
if let Some(override_exclusive_systems) = override_exclusive_systems {
override_exclusive_systems(exclusive_systems_queue.as_mut());
}
*new_entity_created_this_frame = true;
}
yoleck.level_needs_saving = true;
}
}
}
let entity_being_edited;
if let Ok((entity, mut yoleck_managed)) = yoleck_managed_query.single_mut() {
entity_being_edited = Some(entity);
ui.horizontal(|ui| {
ui.heading(format_caption(entity, &yoleck_managed));
if ui.button("Delete").clicked() {
commands.entity(entity).despawn();
writer.write(YoleckEditorEvent::EntityDeselected(entity));
yoleck.level_needs_saving = true;
}
});
ui.horizontal(|ui| {
ui.label("Custom Name:");
ui.text_edit_singleline(&mut yoleck_managed.name);
});
} else {
entity_being_edited = None;
}
if *previously_edited_entity != entity_being_edited {
*previously_edited_entity = entity_being_edited;
for knob_entity in knobs_cache.drain() {
commands.entity(knob_entity).despawn();
}
} else {
knobs_cache.clean_untouched(|knob_entity| {
commands.entity(knob_entity).despawn();
});
}
}
system_state.apply(world);
let frame = egui::Frame::new();
let mut prepared = frame.begin(ui);
let content_ui = std::mem::replace(
&mut prepared.content_ui,
ui.new_child(egui::UiBuilder {
max_rect: Some(ui.max_rect()),
layout: Some(*ui.layout()), // Is this necessary?
..Default::default()
}),
);
world.insert_resource(YoleckUi(content_ui));
world.insert_resource(passed_data);
enum ActiveExclusiveSystemStatus {
DidNotRun,
StillRunningSame,
JustFinishedRunning,
}
let behavior_for_exclusive_system = if let Some(mut active_exclusive_system) =
world.remove_resource::<YoleckActiveExclusiveSystem>()
{
let result = active_exclusive_system
.0
.run((), world)
.map_err(|e| match e {
bevy::ecs::system::RunSystemError::Skipped(e) => e.into(),
bevy::ecs::system::RunSystemError::Failed(e) => e,
})?;
match result {
YoleckExclusiveSystemDirective::Listening => {
world.insert_resource(active_exclusive_system);
ActiveExclusiveSystemStatus::StillRunningSame
}
YoleckExclusiveSystemDirective::Finished => {
ActiveExclusiveSystemStatus::JustFinishedRunning
}
}
} else {
ActiveExclusiveSystemStatus::DidNotRun
};
let should_run_regular_systems = match behavior_for_exclusive_system {
ActiveExclusiveSystemStatus::DidNotRun => loop {
let Some(mut new_exclusive_system) = world
.resource_mut::<YoleckExclusiveSystemsQueue>()
.pop_front()
else {
break true;
};
new_exclusive_system.initialize(world);
let first_run_result =
new_exclusive_system.run((), world).map_err(|e| match e {
bevy::ecs::system::RunSystemError::Skipped(e) => e.into(),
bevy::ecs::system::RunSystemError::Failed(e) => e,
})?;
if *new_entity_created_this_frame
|| matches!(first_run_result, YoleckExclusiveSystemDirective::Listening)
{
world.insert_resource(YoleckActiveExclusiveSystem(new_exclusive_system));
break false;
}
},
ActiveExclusiveSystemStatus::StillRunningSame => false,
ActiveExclusiveSystemStatus::JustFinishedRunning => false,
};
if should_run_regular_systems {
world.resource_scope(|world, mut yoleck_edit_systems: Mut<YoleckEditSystems>| {
yoleck_edit_systems.run_systems(world);
});
}
let YoleckUi(content_ui) = world
.remove_resource()
.expect("The YoleckUi resource was put in the world by this very function");
world.remove_resource::<YoleckPassedData>();
prepared.content_ui = content_ui;
prepared.end(&mut *ui);
// Some systems may have edited the entries, so we need to update them
world.run_schedule(YoleckInternalSchedule::UpdateManagedDataFromComponents);
Ok(())
})
}
================================================
FILE: src/editor_panels.rs
================================================
use bevy::ecs::system::SystemId;
use bevy::prelude::*;
use bevy_egui::egui;
use std::ops::{Deref, DerefMut};
use crate::util::EditSpecificResources;
/// An handle for the egui UI frame used in panel sections definitions
#[derive(Resource)]
pub struct YoleckPanelUi(pub egui::Ui);
impl Deref for YoleckPanelUi {
type Target = egui::Ui;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for YoleckPanelUi {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub(crate) trait EditorPanel: Resource + Sized {
fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>>;
fn wrapper(
&mut self,
ctx: &mut egui::Context,
add_content: impl FnOnce(&mut Self, &mut egui::Ui),
) -> egui::Response;
fn show_panel(world: &mut World, ctx: &mut egui::Context) -> egui::Response {
world.resource_scope(|world, mut this: Mut<Self>| {
this.wrapper(ctx, |this, ui| {
let frame = egui::Frame::new();
let mut prepared = frame.begin(ui);
let content_ui = std::mem::replace(
&mut prepared.content_ui,
ui.new_child(egui::UiBuilder {
max_rect: Some(ui.max_rect()),
layout: Some(*ui.layout()), // Is this necessary?
..Default::default()
}),
);
world.insert_resource(YoleckPanelUi(content_ui));
world.resource_scope(|world, mut edit_specific: Mut<EditSpecificResources>| {
edit_specific.inject_to_world(world);
for section in this.iter_sections() {
world.run_system(section).unwrap().unwrap();
}
edit_specific.take_from_world(world);
});
let YoleckPanelUi(content_ui) = world.remove_resource().expect(
"The YoleckPanelUi resource was put in the world by this very function",
);
prepared.content_ui = content_ui;
prepared.end(ui);
})
})
}
}
/// Sections for the left panel of the Yoleck editor window.
///
/// Already contains sections by default, but can be used to customize the editor by adding more
/// sections. Each section is a Bevy system in the form of a [`SystemId`] with no input and a Bevy
/// [`Result<()>`] for an output. These can be obtained by registering a system function on the
/// Bevy app using [`register_system`](App::register_system).
///
/// The section system can draw on the panel using [`YoleckPanelUi`], accessible as a [`ResMut`].
///
/// ```no_run
/// # use bevy::prelude::*;
/// # use bevy_yoleck::{YoleckEditorLeftPanelSections, egui, YoleckPanelUi};
/// # let mut app = App::new();
/// let time_since_startup_section = app.register_system(|mut ui: ResMut<YoleckPanelUi>, time: Res<Time>| {
/// ui.label(format!("Time since startup is {:?}", time.elapsed()));
/// Ok(())
/// });
/// app.world_mut().resource_mut::<YoleckEditorLeftPanelSections>().0.push(time_since_startup_section);
/// ```
#[derive(Resource)]
pub struct YoleckEditorLeftPanelSections(pub Vec<SystemId<(), Result>>);
impl FromWorld for YoleckEditorLeftPanelSections {
fn from_world(world: &mut World) -> Self {
Self(vec![
world.register_system(crate::editor::new_entity_section),
world.register_system(crate::editor::entity_selection_section),
])
}
}
impl EditorPanel for YoleckEditorLeftPanelSections {
fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
self.0.iter().copied()
}
fn wrapper(
&mut self,
ctx: &mut egui::Context,
add_content: impl FnOnce(&mut Self, &mut egui::Ui),
) -> egui::Response {
egui::SidePanel::left("yoleck_left_panel")
.resizable(true)
.default_width(300.0)
.max_width(ctx.content_rect().width() / 4.0)
.show(ctx, |ui| {
ui.heading("Level Hierarchy");
ui.separator();
egui::ScrollArea::vertical().show(ui, |ui| {
add_content(self, ui);
});
})
.response
}
}
/// Sections for the right panel of the Yoleck editor window. Works the same as
/// [`YoleckEditorLeftPanelSections`].
#[derive(Resource)]
pub struct YoleckEditorRightPanelSections(pub Vec<SystemId<(), Result>>);
impl FromWorld for YoleckEditorRightPanelSections {
fn from_world(world: &mut World) -> Self {
Self(vec![
world.register_system(crate::editor::entity_editing_section),
])
}
}
impl EditorPanel for YoleckEditorRightPanelSections {
fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
self.0.iter().copied()
}
fn wrapper(
&mut self,
ctx: &mut egui::Context,
add_content: impl FnOnce(&mut Self, &mut egui::Ui),
) -> egui::Response {
egui::SidePanel::right("yoleck_right_panel")
.resizable(true)
.default_width(300.0)
.max_width(ctx.content_rect().width() / 4.0)
.show(ctx, |ui| {
ui.heading("Properties");
ui.separator();
egui::ScrollArea::vertical().show(ui, |ui| {
add_content(self, ui);
});
})
.response
}
}
/// Sections for the top panel of the Yoleck editor window. Works the same as
/// [`YoleckEditorLeftPanelSections`].
#[derive(Resource)]
pub struct YoleckEditorTopPanelSections(pub Vec<SystemId<(), Result>>);
impl FromWorld for YoleckEditorTopPanelSections {
fn from_world(world: &mut World) -> Self {
Self(vec![
world.register_system(crate::level_files_manager::level_files_manager_top_section),
world.register_system(crate::level_files_manager::playtest_buttons_section),
])
}
}
impl EditorPanel for YoleckEditorTopPanelSections {
fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
self.0.iter().copied()
}
fn wrapper(
&mut self,
ctx: &mut egui::Context,
add_content: impl FnOnce(&mut Self, &mut egui::Ui),
) -> egui::Response {
egui::TopBottomPanel::top("yoleck_top_panel")
.resizable(false)
.show(ctx, |ui| {
let inner_margin = 3.;
ui.add_space(inner_margin);
ui.horizontal(|ui| {
ui.add_space(inner_margin);
ui.label("Yoleck Editor");
ui.separator();
add_content(self, ui);
ui.add_space(inner_margin);
});
ui.add_space(inner_margin);
})
.response
}
}
/// A tab in the bottom panel of the Yoleck editor window.
///
/// The [`sections`](Self::sections) parameter is a list of [`SystemId`] obtained similarly to the
/// ones in [`YoleckEditorLeftPanelSections`].
pub struct YoleckEditorBottomPanelTab {
pub name: String,
pub sections: Vec<SystemId<(), Result>>,
}
/// Tabs for the bottom panel of the Yoleck editor window.
///
/// Works similar to [`YoleckEditorLeftPanelSections`], except instead of a single list of systems
/// they reside within [`tabs`](Self::tabs).
#[derive(Resource)]
pub struct YoleckEditorBottomPanelSections {
pub tabs: Vec<YoleckEditorBottomPanelTab>,
active_tab: usize,
}
impl FromWorld for YoleckEditorBottomPanelSections {
fn from_world(world: &mut World) -> Self {
Self {
tabs: vec![YoleckEditorBottomPanelTab {
name: "Console".to_owned(),
sections: vec![world.register_system(crate::console::console_panel_section)],
}],
active_tab: 0,
}
}
}
impl EditorPanel for YoleckEditorBottomPanelSections {
fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
self.tabs
.get(self.active_tab)
.into_iter()
.flat_map(|tab| tab.sections.iter().copied())
}
fn wrapper(
&mut self,
ctx: &mut egui::Context,
add_content: impl FnOnce(&mut Self, &mut egui::Ui),
) -> egui::Response {
egui::TopBottomPanel::bottom("yoleck_bottom_panel")
gitextract_d08yw1cr/
├── .cargo/
│ └── config.toml
├── .github/
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── MIGRATION-GUIDES.md
├── README.md
├── assets/
│ ├── levels2d/
│ │ ├── .gitkeep
│ │ └── example.yol
│ ├── levels3d/
│ │ ├── .gitkeep
│ │ └── example.yol
│ ├── levels_doors/
│ │ ├── entry.yol
│ │ ├── index.yoli
│ │ ├── room1.yol
│ │ ├── room2.yol
│ │ └── room3.yol
│ ├── models/
│ │ ├── planet.blend
│ │ ├── planet.glb
│ │ ├── spaceship.blend
│ │ └── spaceship.glb
│ ├── sprites/
│ │ ├── doorway.pxo
│ │ ├── fruits.pxo
│ │ └── player.pxo
│ └── these-assets-are-for-the-examples
├── examples/
│ ├── custom_camera3d.rs
│ ├── doors_to_other_levels.rs
│ ├── example2d.rs
│ └── example3d.rs
├── macros/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs
├── run-retrospective-crate-version-tagging.sh
├── src/
│ ├── auto_edit.rs
│ ├── console.rs
│ ├── editing.rs
│ ├── editor.rs
│ ├── editor_panels.rs
│ ├── editor_window.rs
│ ├── entity_management.rs
│ ├── entity_ref.rs
│ ├── entity_upgrading.rs
│ ├── entity_uuid.rs
│ ├── errors.rs
│ ├── exclusive_systems.rs
│ ├── knobs.rs
│ ├── level_files_manager.rs
│ ├── level_files_upgrading.rs
│ ├── level_index.rs
│ ├── lib.rs
│ ├── picking_helpers.rs
│ ├── populating.rs
│ ├── specs_registration.rs
│ ├── util.rs
│ ├── vpeol.rs
│ ├── vpeol_2d.rs
│ └── vpeol_3d.rs
└── tests/
└── upgrade_level_file.rs
SYMBOL INDEX (496 symbols across 30 files)
FILE: examples/custom_camera3d.rs
constant CAMERA_MODE_ISOMETRIC (line 11) | const CAMERA_MODE_ISOMETRIC: Vpeol3dCameraMode = Vpeol3dCameraMode::Cust...
constant CAMERA_MODE_ORBITAL (line 13) | const CAMERA_MODE_ORBITAL: Vpeol3dCameraMode = Vpeol3dCameraMode::Custom...
function main (line 15) | fn main() {
function setup_camera (line 109) | fn setup_camera(mut commands: Commands) {
function setup_scene (line 128) | fn setup_scene(
function isometric_camera_movement (line 148) | fn isometric_camera_movement(
function orbital_camera_movement (line 201) | fn orbital_camera_movement(
type IsCube (line 251) | struct IsCube;
function populate_cube (line 253) | fn populate_cube(
type IsSphere (line 277) | struct IsSphere;
function populate_sphere (line 279) | fn populate_sphere(
FILE: examples/doors_to_other_levels.rs
function main (line 12) | fn main() {
function setup_camera (line 96) | fn setup_camera(mut commands: Commands) {
type IsPlayer (line 106) | struct IsPlayer;
function populate_player (line 108) | fn populate_player(
function control_camera (line 124) | fn control_camera(
function control_player (line 146) | fn control_player(
type TextContent (line 171) | struct TextContent {
function edit_text (line 175) | fn edit_text(
function populate_text (line 188) | fn populate_text(mut populate: YoleckPopulate<&TextContent>, asset_serve...
type Doorway (line 212) | struct Doorway {
function edit_doorway (line 217) | fn edit_doorway(
function edit_doorway_rotation (line 244) | fn edit_doorway_rotation(
function populate_doorway (line 267) | fn populate_doorway(
function set_doorways_sprite_index (line 300) | fn set_doorways_sprite_index(mut query: Query<(&mut Sprite, Has<DoorIsOp...
type LevelFromOpenedDoor (line 309) | struct LevelFromOpenedDoor {
type PlayerHoldingLevel (line 314) | struct PlayerHoldingLevel;
function handle_player_entity_when_level_loads (line 316) | fn handle_player_entity_when_level_loads(
type DoorIsOpen (line 351) | struct DoorIsOpen;
type DoorConnectsTo (line 354) | struct DoorConnectsTo(Entity);
function handle_door_opening (line 356) | fn handle_door_opening(
function position_level_from_opened_door (line 392) | fn position_level_from_opened_door(
function close_old_doors (line 445) | fn close_old_doors(
FILE: examples/example2d.rs
function main (line 16) | fn main() {
function setup_camera (line 159) | fn setup_camera(mut commands: Commands) {
function setup_assets (line 168) | fn setup_assets(world: &mut World) {
type GameAssets (line 173) | struct GameAssets {
method from_world (line 181) | fn from_world(world: &mut World) -> Self {
type IsPlayer (line 232) | struct IsPlayer;
function populate_player (line 234) | fn populate_player(
function edit_player (line 250) | fn edit_player(
function control_player (line 272) | fn control_player(
type IsFruit (line 301) | struct IsFruit;
type FruitType (line 306) | struct FruitType {
function duplicate_fruit (line 310) | fn duplicate_fruit(
function edit_fruit_type (line 331) | fn edit_fruit_type(
function populate_fruit (line 402) | fn populate_fruit(
function eat_fruits (line 429) | fn eat_fruits(
type TextContent (line 454) | pub struct TextContent {
type TextLaserPointer (line 470) | struct TextLaserPointer {
function populate_text (line 475) | fn populate_text(mut populate: YoleckPopulate<&TextContent>, assets: Res...
type TriangleVertices (line 493) | pub struct TriangleVertices {
method default (line 498) | fn default() -> Self {
function edit_triangle (line 509) | fn edit_triangle(
function populate_triangle (line 534) | fn populate_triangle(
function draw_laser_pointers (line 577) | fn draw_laser_pointers(
FILE: examples/example3d.rs
function main (line 10) | fn main() {
function setup_camera (line 95) | fn setup_camera(mut commands: Commands) {
function setup_arena (line 114) | fn setup_arena(
type IsSpaceship (line 139) | struct IsSpaceship;
type SpaceshipSettings (line 142) | struct SpaceshipSettings {
method default (line 152) | fn default() -> Self {
function populate_spaceship (line 161) | fn populate_spaceship(
function control_spaceship (line 173) | fn control_spaceship(
type IsPlanet (line 208) | struct IsPlanet;
function populate_planet (line 210) | fn populate_planet(
function hit_planets (line 222) | fn hit_planets(
type SimpleSphere (line 247) | struct SimpleSphere;
type LaserPointer (line 260) | struct LaserPointer {
function populate_simple_sphere (line 265) | fn populate_simple_sphere(
function draw_laser_pointers (line 285) | fn draw_laser_pointers(
FILE: macros/src/lib.rs
function derive_yoleck_component (line 7) | pub fn derive_yoleck_component(input: proc_macro::TokenStream) -> proc_m...
function impl_yoleck_component_derive (line 15) | fn impl_yoleck_component_derive(input: DeriveInput) -> Result<TokenStrea...
type YoleckFieldAttrs (line 27) | struct YoleckFieldAttrs {
function parse_number (line 41) | fn parse_number(expr: &syn::Expr) -> syn::Result<f64> {
function parse_field_attrs (line 60) | fn parse_field_attrs(field: &Field) -> Result<YoleckFieldAttrs, Error> {
function get_type_name (line 155) | fn get_type_name(ty: &Type) -> String {
function quote_option (line 167) | fn quote_option<T, F>(opt: &Option<T>, f: F) -> TokenStream
function generate_field_ui (line 180) | fn generate_field_ui(field: &Field, attrs: &YoleckFieldAttrs) -> TokenSt...
function derive_yoleck_auto_edit (line 219) | pub fn derive_yoleck_auto_edit(input: proc_macro::TokenStream) -> proc_m...
function impl_yoleck_auto_edit_derive (line 227) | fn impl_yoleck_auto_edit_derive(input: DeriveInput) -> Result<TokenStrea...
type EntityRefFieldInfo (line 343) | struct EntityRefFieldInfo {
function parse_entity_ref_attrs (line 348) | fn parse_entity_ref_attrs(field: &Field) -> Result<Option<EntityRefField...
FILE: src/auto_edit.rs
type FieldAttrs (line 16) | pub struct FieldAttrs {
type YoleckAutoEdit (line 26) | pub trait YoleckAutoEdit: Send + Sync + 'static {
method auto_edit (line 27) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui);
method auto_edit_with_label_and_attrs (line 31) | fn auto_edit_with_label_and_attrs(
method auto_edit_field_impl (line 48) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 69) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 73) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 91) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 95) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 143) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 147) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 159) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 163) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 185) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 192) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 217) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 225) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 255) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 264) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 299) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 343) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 397) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 408) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 430) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 446) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 471) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 490) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
method auto_edit (line 517) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit (line 534) | fn auto_edit(value: &mut Self, ui: &mut egui::Ui) {
method auto_edit_field_impl (line 547) | fn auto_edit_field_impl(value: &mut Self, ui: &mut egui::Ui, label: &s...
function render_auto_edit_value (line 64) | pub fn render_auto_edit_value<T: YoleckAutoEdit>(ui: &mut egui::Ui, valu...
type EntityRefDisplayInfo (line 528) | struct EntityRefDisplayInfo {
function auto_edit_system (line 628) | pub fn auto_edit_system<T: YoleckComponent + YoleckAutoEdit + YoleckEnti...
type YoleckAutoEditExt (line 670) | pub trait YoleckAutoEditExt {
method add_yoleck_auto_edit (line 671) | fn add_yoleck_auto_edit<
method add_yoleck_auto_edit (line 682) | fn add_yoleck_auto_edit<
FILE: src/console.rs
type LogLevel (line 13) | pub enum LogLevel {
method color (line 21) | pub fn color(&self) -> egui::Color32 {
method label (line 30) | pub fn label(&self) -> &str {
type LogEntry (line 42) | pub struct LogEntry {
type CapturedLogMessages (line 49) | pub struct CapturedLogMessages(mpsc::Receiver<LogEntry>);
type YoleckConsoleLogHistory (line 53) | pub struct YoleckConsoleLogHistory {
method new (line 59) | pub fn new(max_logs: usize) -> Self {
method add_log (line 66) | pub fn add_log(&mut self, entry: LogEntry) {
method clear (line 73) | pub fn clear(&mut self) {
method default (line 79) | fn default() -> Self {
type YoleckConsoleState (line 86) | pub struct YoleckConsoleState {
type LogFilters (line 92) | pub struct LogFilters {
method should_show (line 111) | pub fn should_show(&self, level: LogLevel) -> bool {
method default (line 100) | fn default() -> Self {
function console_panel_section (line 122) | pub fn console_panel_section(
type YoleckConsoleLayer (line 164) | pub struct YoleckConsoleLayer {
method new (line 169) | pub fn new(sender: mpsc::Sender<LogEntry>) -> Self {
method on_event (line 178) | fn on_event(
type MessageVisitor (line 206) | struct MessageVisitor {
method record_debug (line 211) | fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn ...
function transfer_log_messages (line 218) | fn transfer_log_messages(
function store_log_messages (line 225) | fn store_log_messages(
function console_layer_factory (line 257) | pub fn console_layer_factory(app: &mut App) -> Option<BoxedLayer> {
FILE: src/editing.rs
type YoleckEditMarker (line 10) | pub struct YoleckEditMarker;
type YoleckEdit (line 21) | pub struct YoleckEdit<'w, 's, Q: 'static + QueryData, F: 'static + Query...
function single (line 27) | pub fn single(
function single_mut (line 36) | pub fn single_mut(&mut self) -> Result<<Q as QueryData>::Item<'_, 's>, Q...
function is_empty (line 43) | pub fn is_empty(&self) -> bool {
function has_nonmatching (line 51) | pub fn has_nonmatching(&self) -> bool {
function iter_matching (line 62) | pub fn iter_matching(
function iter_matching_mut (line 74) | pub fn iter_matching_mut(&mut self) -> QueryIter<'_, '_, Q, (With<Yoleck...
type YoleckUi (line 81) | pub struct YoleckUi(pub egui::Ui);
type Target (line 84) | type Target = egui::Ui;
method deref (line 86) | fn deref(&self) -> &Self::Target {
method deref_mut (line 92) | fn deref_mut(&mut self) -> &mut Self::Target {
FILE: src/editor.rs
type YoleckEditorState (line 29) | pub enum YoleckEditorState {
type YoleckSyncWithEditorState (line 73) | pub struct YoleckSyncWithEditorState<T>
method build (line 101) | fn build(&self, app: &mut App) {
type YoleckEditorEvent (line 123) | pub enum YoleckEditorEvent {
type YoleckDirectiveInner (line 129) | enum YoleckDirectiveInner {
type YoleckDirective (line 149) | pub struct YoleckDirective(YoleckDirectiveInner);
method pass_to_entity (line 157) | pub fn pass_to_entity<T: 'static + Send + Sync>(entity: Entity, data: ...
method set_selected (line 166) | pub fn set_selected(entity: Option<Entity>) -> Self {
method toggle_selected (line 171) | pub fn toggle_selected(entity: Entity) -> Self {
method spawn_entity (line 209) | pub fn spawn_entity(
method from (line 272) | fn from(value: SpawnEntityBuilder) -> Self {
type SpawnEntityBuilder (line 224) | pub struct SpawnEntityBuilder {
method with (line 235) | pub fn with<T: YoleckComponent>(self, component: T) -> Self {
method with_raw (line 242) | pub fn with_raw(
method extend (line 251) | pub fn extend(
method modify_exclusive_systems (line 262) | pub fn modify_exclusive_systems(
type YoleckPassedData (line 288) | pub struct YoleckPassedData(pub(crate) HashMap<Entity, HashMap<TypeId, B...
method get (line 313) | pub fn get<T: 'static>(&self, entity: Entity) -> Option<&T> {
function format_caption (line 324) | fn format_caption(entity: Entity, yoleck_managed: &YoleckManaged) -> Str...
function new_entity_section (line 336) | pub fn new_entity_section(
function entity_selection_section (line 372) | pub fn entity_selection_section(
function entity_editing_section (line 489) | pub fn entity_editing_section(
FILE: src/editor_panels.rs
type YoleckPanelUi (line 10) | pub struct YoleckPanelUi(pub egui::Ui);
type Target (line 13) | type Target = egui::Ui;
method deref (line 15) | fn deref(&self) -> &Self::Target {
method deref_mut (line 21) | fn deref_mut(&mut self) -> &mut Self::Target {
type EditorPanel (line 26) | pub(crate) trait EditorPanel: Resource + Sized {
method iter_sections (line 27) | fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>>;
method wrapper (line 28) | fn wrapper(
method show_panel (line 34) | fn show_panel(world: &mut World, ctx: &mut egui::Context) -> egui::Res...
method iter_sections (line 99) | fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
method wrapper (line 103) | fn wrapper(
method iter_sections (line 137) | fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
method wrapper (line 141) | fn wrapper(
method iter_sections (line 176) | fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
method wrapper (line 180) | fn wrapper(
method iter_sections (line 236) | fn iter_sections(&self) -> impl Iterator<Item = SystemId<(), Result>> {
method wrapper (line 243) | fn wrapper(
type YoleckEditorLeftPanelSections (line 87) | pub struct YoleckEditorLeftPanelSections(pub Vec<SystemId<(), Result>>);
method from_world (line 90) | fn from_world(world: &mut World) -> Self {
type YoleckEditorRightPanelSections (line 126) | pub struct YoleckEditorRightPanelSections(pub Vec<SystemId<(), Result>>);
method from_world (line 129) | fn from_world(world: &mut World) -> Self {
type YoleckEditorTopPanelSections (line 164) | pub struct YoleckEditorTopPanelSections(pub Vec<SystemId<(), Result>>);
method from_world (line 167) | fn from_world(world: &mut World) -> Self {
type YoleckEditorBottomPanelTab (line 208) | pub struct YoleckEditorBottomPanelTab {
type YoleckEditorBottomPanelSections (line 218) | pub struct YoleckEditorBottomPanelSections {
method from_world (line 224) | fn from_world(world: &mut World) -> Self {
FILE: src/editor_window.rs
type YoleckEditorViewportRect (line 12) | pub struct YoleckEditorViewportRect {
function yoleck_editor_window (line 16) | pub(crate) fn yoleck_editor_window(
FILE: src/entity_management.rs
type YoleckEntryHeader (line 24) | pub struct YoleckEntryHeader {
type YoleckRawEntry (line 43) | pub struct YoleckRawEntry {
method deserialize (line 58) | fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
method serialize (line 49) | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
function yoleck_process_raw_entries (line 67) | pub(crate) fn yoleck_process_raw_entries(
function yoleck_prepare_populate_schedule (line 121) | pub(crate) fn yoleck_prepare_populate_schedule(
function yoleck_run_populate_schedule (line 153) | pub(crate) fn yoleck_run_populate_schedule(world: &mut World) {
type EntitiesToPopulate (line 159) | pub(crate) struct EntitiesToPopulate(pub Vec<(Entity, PopulateReason)>);
function process_loading_command (line 161) | pub(crate) fn process_loading_command(
function yoleck_run_post_load_resolutions_schedule (line 188) | pub(crate) fn yoleck_run_post_load_resolutions_schedule(world: &mut Worl...
function yoleck_run_level_loaded_schedule (line 192) | pub(crate) fn yoleck_run_level_loaded_schedule(world: &mut World) {
function yoleck_remove_just_loaded_marker_from_levels (line 196) | pub(crate) fn yoleck_remove_just_loaded_marker_from_levels(
function process_unloading_command (line 207) | pub(crate) fn process_unloading_command(
type YoleckLoadLevel (line 251) | pub struct YoleckLoadLevel(pub Handle<YoleckRawLevel>);
type YoleckKeepLevel (line 260) | pub struct YoleckKeepLevel;
type YoleckLevelAssetLoader (line 263) | pub(crate) struct YoleckLevelAssetLoader;
type YoleckRawLevel (line 267) | pub struct YoleckRawLevel(
method new (line 281) | pub fn new(
method entries (line 295) | pub fn entries(&self) -> &[YoleckRawEntry] {
method into_entries (line 299) | pub fn into_entries(self) -> impl Iterator<Item = YoleckRawEntry> {
type YoleckRawLevelHeader (line 275) | pub struct YoleckRawLevelHeader {
type Asset (line 305) | type Asset = YoleckRawLevel;
type Settings (line 306) | type Settings = ();
type Error (line 307) | type Error = YoleckAssetLoaderError;
method extensions (line 309) | fn extensions(&self) -> &[&str] {
method load (line 313) | async fn load(
FILE: src/entity_ref.rs
type YoleckEntityRef (line 58) | pub struct YoleckEntityRef {
method new (line 78) | pub fn new() -> Self {
method from_uuid (line 85) | pub fn from_uuid(uuid: Uuid) -> Self {
method is_some (line 92) | pub fn is_some(&self) -> bool {
method is_none (line 96) | pub fn is_none(&self) -> bool {
method entity (line 100) | pub fn entity(&self) -> Option<Entity> {
method uuid (line 104) | pub fn uuid(&self) -> Option<Uuid> {
method clear (line 108) | pub fn clear(&mut self) {
method set (line 113) | pub fn set(&mut self, uuid: Uuid) {
method resolve (line 118) | pub fn resolve(
type YoleckEntityRefAccessor (line 134) | pub trait YoleckEntityRefAccessor: Sized + Send + Sync + 'static {
method entity_ref_fields (line 135) | fn entity_ref_fields() -> &'static [(&'static str, Option<&'static str...
method get_entity_ref_mut (line 136) | fn get_entity_ref_mut(&mut self, field_name: &str) -> &mut YoleckEntit...
method resolve_entity_refs (line 138) | fn resolve_entity_refs(&mut self, registry: &YoleckUuidRegistry);
function validate_entity_ref_requirements_for (line 141) | pub(crate) fn validate_entity_ref_requirements_for<T: YoleckEntityRefAcc...
function resolve_entity_refs (line 160) | pub fn resolve_entity_refs<
FILE: src/entity_upgrading.rs
type YoleckEntityUpgradingPlugin (line 30) | pub struct YoleckEntityUpgradingPlugin {
method build (line 39) | fn build(&self, app: &mut App) {
type YoleckEntityUpgrading (line 48) | pub(crate) struct YoleckEntityUpgrading {
method upgrade_raw_level_file (line 65) | pub fn upgrade_raw_level_file(&self, levels_file: &mut YoleckRawLevel) {
FILE: src/entity_uuid.rs
type YoleckEntityUuid (line 16) | pub struct YoleckEntityUuid(pub(crate) Uuid);
method get (line 19) | pub fn get(&self) -> Uuid {
type YoleckUuidRegistry (line 29) | pub struct YoleckUuidRegistry(pub(crate) HashMap<Uuid, Entity>);
method get (line 32) | pub fn get(&self, uuid: Uuid) -> Option<Entity> {
FILE: src/errors.rs
type YoleckAssetLoaderError (line 5) | pub(crate) enum YoleckAssetLoaderError {
method from (line 18) | fn from(value: BevyError) -> Self {
type YoleckEntityRefCannotBeResolved (line 25) | pub struct YoleckEntityRefCannotBeResolved {
FILE: src/exclusive_systems.rs
type YoleckExclusiveSystemsPlugin (line 5) | pub(crate) struct YoleckExclusiveSystemsPlugin;
method build (line 8) | fn build(&self, app: &mut App) {
type YoleckExclusiveSystemDirective (line 16) | pub enum YoleckExclusiveSystemDirective {
type YoleckExclusiveSystem (line 27) | pub type YoleckExclusiveSystem = Box<dyn System<In = (), Out = YoleckExc...
type YoleckExclusiveSystemsQueue (line 82) | pub struct YoleckExclusiveSystemsQueue(VecDeque<YoleckExclusiveSystem>);
method push_back (line 89) | pub fn push_back<P>(&mut self, system: impl IntoSystem<(), YoleckExclu...
method push_front (line 97) | pub fn push_front<P>(
method clear (line 108) | pub fn clear(&mut self) {
method pop_front (line 112) | pub(crate) fn pop_front(&mut self) -> Option<YoleckExclusiveSystem> {
type YoleckActiveExclusiveSystem (line 118) | pub(crate) struct YoleckActiveExclusiveSystem(pub YoleckExclusiveSystem);
type YoleckEntityCreationExclusiveSystems (line 126) | pub struct YoleckEntityCreationExclusiveSystems(
method on_entity_creation (line 133) | pub fn on_entity_creation(
method create_queue (line 140) | pub(crate) fn create_queue(&self) -> YoleckExclusiveSystemsQueue {
FILE: src/knobs.rs
type YoleckKnobsCache (line 13) | pub struct YoleckKnobsCache {
method access (line 28) | pub fn access<'a, K>(&mut self, key: K, commands: &'a mut Commands) ->...
method clean_untouched (line 56) | pub fn clean_untouched(&mut self, mut clean_func: impl FnMut(Entity)) {
method drain (line 71) | pub fn drain(&mut self) -> impl '_ + Iterator<Item = Entity> {
type YoleckKnobMarker (line 19) | pub struct YoleckKnobMarker;
type CachedKnob (line 21) | struct CachedKnob {
type KnobFromCache (line 78) | pub struct KnobFromCache<'a> {
type YoleckKnobHandle (line 84) | pub struct YoleckKnobHandle<'a> {
function get_passed_data (line 117) | pub fn get_passed_data<T: 'static>(&self) -> Option<&T> {
type YoleckKnobs (line 127) | pub struct YoleckKnobs<'w, 's> {
function knob (line 134) | pub fn knob<K>(&mut self, key: K) -> YoleckKnobHandle<'_>
FILE: src/level_files_manager.rs
constant EXTENSION (line 24) | const EXTENSION: &str = ".yol";
constant EXTENSION_WITHOUT_DOT (line 25) | const EXTENSION_WITHOUT_DOT: &str = "yol";
type YoleckEditorLevelsDirectoryPath (line 41) | pub struct YoleckEditorLevelsDirectoryPath(pub PathBuf);
type SelectedLevelFile (line 44) | enum SelectedLevelFile {
type LevelFilesManagerTopSectionLocals (line 50) | pub struct LevelFilesManagerTopSectionLocals {
method default (line 58) | fn default() -> Self {
function level_files_manager_top_section (line 69) | pub fn level_files_manager_top_section(
function playtest_buttons_section (line 464) | pub fn playtest_buttons_section(
FILE: src/level_files_upgrading.rs
function upgrade_level_file (line 4) | pub fn upgrade_level_file(mut level: serde_json::Value) -> Result<serde_...
function upgrade_level_file_1_to_2 (line 28) | fn upgrade_level_file_1_to_2(parts: &mut [serde_json::Value]) -> Result<...
FILE: src/level_index.rs
type YoleckLevelIndexEntry (line 14) | pub struct YoleckLevelIndexEntry {
type YoleckLevelIndex (line 48) | pub struct YoleckLevelIndex(YoleckLevelIndexHeader, Vec<YoleckLevelIndex...
method new (line 57) | pub fn new(entries: impl IntoIterator<Item = YoleckLevelIndexEntry>) -...
type YoleckLevelIndexHeader (line 52) | pub struct YoleckLevelIndexHeader {
type Target (line 66) | type Target = [YoleckLevelIndexEntry];
method deref (line 68) | fn deref(&self) -> &Self::Target {
type YoleckLevelIndexLoader (line 74) | pub(crate) struct YoleckLevelIndexLoader;
type Asset (line 77) | type Asset = YoleckLevelIndex;
type Settings (line 78) | type Settings = ();
type Error (line 79) | type Error = YoleckAssetLoaderError;
method load (line 81) | async fn load(
method extensions (line 94) | fn extensions(&self) -> &[&str] {
type YoleckEditableLevels (line 101) | pub struct YoleckEditableLevels {
method names (line 107) | pub fn names(&self) -> impl Iterator<Item = &str> {
FILE: src/lib.rs
type YoleckPluginBase (line 258) | struct YoleckPluginBase;
type YoleckPluginForGame (line 259) | pub struct YoleckPluginForGame;
type YoleckPluginForEditor (line 260) | pub struct YoleckPluginForEditor;
type YoleckSystems (line 263) | enum YoleckSystems {
type YoleckRunEditSystems (line 269) | pub(crate) struct YoleckRunEditSystems;
method build (line 272) | fn build(&self, app: &mut App) {
method build (line 347) | fn build(&self, app: &mut App) {
method build (line 360) | fn build(&self, app: &mut App) {
type YoleckExtForApp (line 405) | pub trait YoleckExtForApp {
method add_yoleck_entity_type (line 424) | fn add_yoleck_entity_type(&mut self, entity_type: YoleckEntityType);
method add_yoleck_edit_system (line 445) | fn add_yoleck_edit_system<P>(&mut self, system: impl 'static + IntoSys...
method add_yoleck_entity_upgrade (line 452) | fn add_yoleck_entity_upgrade(
method add_yoleck_entity_upgrade_for (line 463) | fn add_yoleck_entity_upgrade_for(
method add_yoleck_entity_type (line 479) | fn add_yoleck_entity_type(&mut self, entity_type: YoleckEntityType) {
method add_yoleck_edit_system (line 525) | fn add_yoleck_edit_system<P>(&mut self, system: impl 'static + IntoSys...
method add_yoleck_entity_upgrade (line 533) | fn add_yoleck_entity_upgrade(
type BoxedArc (line 557) | type BoxedArc = Arc<dyn Send + Sync + Any>;
type BoxedAny (line 558) | type BoxedAny = Box<dyn Send + Sync + Any>;
type YoleckManaged (line 562) | pub struct YoleckManaged {
type YoleckBelongsToLevel (line 591) | pub struct YoleckBelongsToLevel {
type YoleckEntityLifecycleStatus (line 597) | pub enum YoleckEntityLifecycleStatus {
type YoleckEditSystems (line 604) | struct YoleckEditSystems {
method run_systems (line 609) | pub(crate) fn run_systems(&mut self, world: &mut World) {
type YoleckEntityTypeInfo (line 618) | pub(crate) struct YoleckEntityTypeInfo {
type YoleckEntityConstructionSpecs (line 628) | pub(crate) struct YoleckEntityConstructionSpecs {
method get_entity_type_info (line 635) | pub fn get_entity_type_info(&self, entity_type: &str) -> Option<&Yolec...
type YoleckState (line 642) | pub(crate) struct YoleckState {
type YoleckPlaytestLevel (line 649) | pub struct YoleckPlaytestLevel(pub Option<YoleckRawLevel>);
type YoleckInternalSchedule (line 652) | pub(crate) enum YoleckInternalSchedule {
type YoleckSchedule (line 662) | pub enum YoleckSchedule {
type YoleckLevelInEditor (line 695) | pub struct YoleckLevelInEditor;
type YoleckLevelInPlaytest (line 702) | pub struct YoleckLevelInPlaytest;
type YoleckLevelJustLoaded (line 710) | pub struct YoleckLevelJustLoaded;
FILE: src/picking_helpers.rs
function yoleck_map_entity_to_uuid (line 12) | pub fn yoleck_map_entity_to_uuid(
function yoleck_exclusive_system_cancellable (line 22) | pub fn yoleck_exclusive_system_cancellable(
FILE: src/populating.rs
type YoleckPopulate (line 12) | pub struct YoleckPopulate<'w, 's, Q: 'static + QueryData, F: 'static + Q...
function populate (line 21) | pub fn populate(
type PopulateReason (line 38) | pub(crate) enum PopulateReason {
type YoleckPopulateContext (line 45) | pub struct YoleckPopulateContext {
method is_in_editor (line 51) | pub fn is_in_editor(&self) -> bool {
method is_first_time (line 61) | pub fn is_first_time(&self) -> bool {
type YoleckSystemMarker (line 72) | pub struct YoleckSystemMarker(usize);
type MarkerGenerator (line 75) | struct MarkerGenerator(RangeFrom<usize>);
method from_world (line 78) | fn from_world(world: &mut World) -> Self {
type YoleckMarking (line 109) | pub struct YoleckMarking<'w, 's> {
function marker (line 117) | pub fn marker(&self) -> YoleckSystemMarker {
function despawn_marked (line 123) | pub fn despawn_marked(&self, cmd: &mut EntityCommands) {
FILE: src/specs_registration.rs
type YoleckComponent (line 18) | pub trait YoleckComponent:
constant KEY (line 21) | const KEY: &'static str;
type YoleckEntityType (line 30) | pub struct YoleckEntityType {
method new (line 41) | pub fn new(name: impl ToString) -> Self {
method with (line 51) | pub fn with<T: YoleckComponent>(mut self) -> Self {
method insert_on_init (line 60) | pub fn insert_on_init<T: Bundle>(
method insert_on_init_during_editor (line 72) | pub fn insert_on_init_during_editor<T: Bundle>(
method insert_on_init_during_game (line 86) | pub fn insert_on_init_during_game<T: Bundle>(
method with_uuid (line 126) | pub fn with_uuid(mut self) -> Self {
type YoleckComponentHandler (line 132) | pub(crate) trait YoleckComponentHandler: 'static + Sync + Send {
method component_type (line 133) | fn component_type(&self) -> TypeId;
method key (line 134) | fn key(&self) -> &'static str;
method init_in_entity (line 135) | fn init_in_entity(
method build_in_bevy_app (line 141) | fn build_in_bevy_app(&self, app: &mut App);
method serialize (line 142) | fn serialize(&self, component: &dyn Any) -> serde_json::Value;
method component_type (line 151) | fn component_type(&self) -> TypeId {
method key (line 155) | fn key(&self) -> &'static str {
method init_in_entity (line 159) | fn init_in_entity(
method build_in_bevy_app (line 180) | fn build_in_bevy_app(&self, app: &mut App) {
method serialize (line 188) | fn serialize(&self, component: &dyn Any) -> serde_json::Value {
type YoleckComponentHandlerImpl (line 146) | struct YoleckComponentHandlerImpl<T: YoleckComponent> {
function update_data_from_components (line 197) | fn update_data_from_components(mut query: Query<(&mut YoleckManaged, &mu...
FILE: src/util.rs
type ContextSpecificResource (line 3) | trait ContextSpecificResource: 'static + Sync + Send {
method inject_to_world (line 4) | fn inject_to_world(&mut self, world: &mut World);
method take_from_world (line 5) | fn take_from_world(&mut self, world: &mut World);
method inject_to_world (line 12) | fn inject_to_world(&mut self, world: &mut World) {
method take_from_world (line 16) | fn take_from_world(&mut self, world: &mut World) {
type EditSpecificResources (line 22) | pub(crate) struct EditSpecificResources(Vec<Box<dyn ContextSpecificResou...
method new (line 25) | pub fn new() -> Self {
method with (line 29) | pub fn with(mut self, resource: impl Resource) -> Self {
method inject_to_world (line 34) | pub fn inject_to_world(&mut self, world: &mut World) {
method take_from_world (line 40) | pub fn take_from_world(&mut self, world: &mut World) {
FILE: src/vpeol.rs
type VpeolSystems (line 47) | pub enum VpeolSystems {
type VpeolBasePlugin (line 62) | pub struct VpeolBasePlugin;
method build (line 65) | fn build(&self, app: &mut App) {
type VpeolDragPlane (line 111) | pub struct VpeolDragPlane(pub InfinitePlane3d);
constant XY (line 114) | pub const XY: VpeolDragPlane = VpeolDragPlane(InfinitePlane3d { normal...
constant XZ (line 115) | pub const XZ: VpeolDragPlane = VpeolDragPlane(InfinitePlane3d { normal...
type VpeolCameraState (line 120) | pub struct VpeolCameraState {
method consider (line 161) | pub fn consider(
method pointing_at_entity (line 194) | pub fn pointing_at_entity(&self, entity: Entity) -> Option<&VpeolCurso...
type VpeolCursorPointing (line 134) | pub struct VpeolCursorPointing {
type VpeolClicksOnObjectsState (line 143) | pub enum VpeolClicksOnObjectsState {
function prepare_camera_state (line 204) | fn prepare_camera_state(
function update_camera_world_position (line 221) | fn update_camera_world_position(
type WindowGetter (line 245) | pub(crate) struct WindowGetter<'w, 's> {
function get_window (line 251) | pub fn get_window(&self, window_ref: WindowRef) -> Option<&Window> {
function handle_camera_state (line 260) | fn handle_camera_state(
type YoleckKnobClick (line 426) | pub struct YoleckKnobClick;
type VpeolWillContainClickableChildren (line 433) | pub struct VpeolWillContainClickableChildren;
type VpeolRouteClickTo (line 437) | pub struct VpeolRouteClickTo(pub Entity);
type VpeolRootResolver (line 442) | pub struct VpeolRootResolver<'w, 's> {
function resolve_root (line 450) | pub fn resolve_root(&self, entity: Entity) -> Option<Entity> {
function handle_clickable_children_system (line 461) | pub fn handle_clickable_children_system<F, B>(
type VpeolSelectionCuePlugin (line 496) | pub struct VpeolSelectionCuePlugin {
method default (line 504) | fn default() -> Self {
method build (line 513) | fn build(&self, app: &mut App) {
type SelectionCueAnimation (line 530) | struct SelectionCueAnimation {
function manage_selection_transform_components (line 535) | fn manage_selection_transform_components(
function add_selection_cue_before_transform_propagate (line 551) | fn add_selection_cue_before_transform_propagate(
function restore_transform_from_cache_after_transform_propagate (line 571) | fn restore_transform_from_cache_after_transform_propagate(
function ray_intersection_with_mesh (line 579) | pub(crate) fn ray_intersection_with_mesh(ray: Ray3d, mesh: &Mesh) -> Opt...
function ray_intersection_with_aabb (line 590) | fn ray_intersection_with_aabb(ray: Ray3d, aabb: Aabb) -> Option<f32> {
function iter_triangles (line 626) | fn iter_triangles(mesh: &Mesh) -> Option<impl '_ + Iterator<Item = Trian...
type Triangle (line 645) | struct Triangle([Vec3; 3]);
method ray_intersection (line 648) | fn ray_intersection(&self, ray: Ray3d) -> Option<f32> {
function vpeol_read_click_on_entity (line 682) | pub fn vpeol_read_click_on_entity<Filter: QueryFilter>(
type VpeolRepositionLevel (line 739) | pub struct VpeolRepositionLevel(pub Transform);
function handle_delete_entity_key (line 741) | fn handle_delete_entity_key(
type VpeolClipboard (line 767) | enum VpeolClipboard {
method from_world (line 774) | fn from_world(_: &mut World) -> Self {
function handle_copy_entity_key (line 789) | fn handle_copy_entity_key(
function handle_paste_entity_key (line 851) | fn handle_paste_entity_key(
FILE: src/vpeol_2d.rs
type Vpeol2dPluginForGame (line 109) | pub struct Vpeol2dPluginForGame;
method build (line 112) | fn build(&self, app: &mut App) {
function register_reflect_types (line 123) | fn register_reflect_types(app: &mut App) {
type Vpeol2dPluginForEditor (line 136) | pub struct Vpeol2dPluginForEditor;
method build (line 139) | fn build(&self, app: &mut App) {
type CursorInWorldPos (line 177) | struct CursorInWorldPos {
method from_camera_state (line 182) | fn from_camera_state(camera_state: &VpeolCameraState) -> Option<Self> {
method cursor_in_entity_space (line 188) | fn cursor_in_entity_space(&self, transform: &GlobalTransform) -> Vec2 {
method check_square (line 196) | fn check_square(
function update_camera_status_for_sprites (line 218) | fn update_camera_status_for_sprites(
function update_camera_status_for_2d_meshes (line 263) | fn update_camera_status_for_2d_meshes(
function update_camera_status_for_text_2d (line 302) | fn update_camera_status_for_text_2d(
type Vpeol2dCameraControl (line 332) | pub struct Vpeol2dCameraControl {
method default (line 340) | fn default() -> Self {
function camera_2d_pan (line 348) | fn camera_2d_pan(
function camera_2d_zoom (line 395) | fn camera_2d_zoom(
type Vpeol2dPosition (line 462) | pub struct Vpeol2dPosition(pub Vec2);
type Vpeol2dRotatation (line 470) | pub struct Vpeol2dRotatation(pub f32);
type Vpeol2dScale (line 478) | pub struct Vpeol2dScale(pub Vec2);
method default (line 481) | fn default() -> Self {
function vpeol_2d_edit_transform_group (line 486) | fn vpeol_2d_edit_transform_group(
function vpeol_2d_edit_position_impl (line 508) | fn vpeol_2d_edit_position_impl(
function vpeol_2d_edit_rotation_impl (line 545) | fn vpeol_2d_edit_rotation_impl(ui: &mut egui::Ui, mut edit: YoleckEdit<&...
function vpeol_2d_edit_scale_impl (line 580) | fn vpeol_2d_edit_scale_impl(ui: &mut egui::Ui, mut edit: YoleckEdit<&mut...
function vpeol_2d_init_position (line 636) | fn vpeol_2d_init_position(
function vpeol_2d_populate_transform (line 667) | fn vpeol_2d_populate_transform(
FILE: src/vpeol_3d.rs
type Vpeol3dPluginForGame (line 152) | pub struct Vpeol3dPluginForGame;
method build (line 155) | fn build(&self, app: &mut App) {
function register_reflect_types (line 166) | fn register_reflect_types(app: &mut App) {
type Vpeol3dPluginForEditor (line 179) | pub struct Vpeol3dPluginForEditor {
method sidescroller (line 194) | pub fn sidescroller() -> Self {
method topdown (line 205) | pub fn topdown() -> Self {
method build (line 213) | fn build(&self, app: &mut App) {
function update_camera_status_for_models (line 267) | fn update_camera_status_for_models(
type YoleckCameraChoice (line 318) | pub struct YoleckCameraChoice {
type YoleckCameraChoices (line 354) | pub struct YoleckCameraChoices {
method new (line 359) | pub fn new() -> Self {
method choice (line 368) | pub fn choice(mut self, name: impl Into<String>, control: Vpeol3dCamer...
method choice_with_transform (line 381) | pub fn choice_with_transform(
method default (line 399) | fn default() -> Self {
type Vpeol3dCameraMode (line 432) | pub enum Vpeol3dCameraMode {
type Vpeol3dCameraControl (line 446) | pub struct Vpeol3dCameraControl {
method fps (line 474) | pub fn fps() -> Self {
method sidescroller (line 491) | pub fn sidescroller() -> Self {
method topdown (line 509) | pub fn topdown() -> Self {
function camera_3d_wasd_movement (line 524) | fn camera_3d_wasd_movement(
function camera_3d_move_along_plane_normal (line 621) | fn camera_3d_move_along_plane_normal(
function draw_scene_gizmo (line 652) | fn draw_scene_gizmo(
function camera_3d_rotate (line 888) | fn camera_3d_rotate(
function vpeol_3d_translation_gizmo_mode_selector (line 956) | pub fn vpeol_3d_translation_gizmo_mode_selector(
function vpeol_3d_camera_mode_selector (line 980) | pub fn vpeol_3d_camera_mode_selector(
type Vpeol3dPosition (line 1031) | pub struct Vpeol3dPosition(pub Vec3);
type Vpeol3dSnapToPlane (line 1044) | pub struct Vpeol3dSnapToPlane {
type Vpeol3dTranslationGizmoMode (line 1051) | pub enum Vpeol3dTranslationGizmoMode {
type Vpeol3dTranslationGizmoConfig (line 1057) | pub struct Vpeol3dTranslationGizmoConfig {
method default (line 1064) | fn default() -> Self {
type Vpeol3dRotation (line 1079) | pub struct Vpeol3dRotation(pub Quat);
method default (line 1082) | fn default() -> Self {
type Vpeol3dScale (line 1093) | pub struct Vpeol3dScale(pub Vec3);
method default (line 1096) | fn default() -> Self {
type CommonDragPlane (line 1101) | enum CommonDragPlane {
method consider (line 1108) | fn consider(&mut self, normal: Vec3) {
method shared_normal (line 1122) | fn shared_normal(&self) -> Option<Vec3> {
function vpeol_3d_edit_transform_group (line 1131) | fn vpeol_3d_edit_transform_group(
function vpeol_3d_edit_position_impl (line 1159) | fn vpeol_3d_edit_position_impl(
function vpeol_3d_edit_rotation_impl (line 1220) | fn vpeol_3d_edit_rotation_impl(ui: &mut egui::Ui, mut edit: YoleckEdit<&...
function vpeol_3d_edit_scale_impl (line 1281) | fn vpeol_3d_edit_scale_impl(ui: &mut egui::Ui, mut edit: YoleckEdit<&mut...
function vpeol_3d_init_position (line 1343) | fn vpeol_3d_init_position(
type AxisKnobData (line 1381) | struct AxisKnobData {
function vpeol_3d_edit_axis_knobs (line 1387) | fn vpeol_3d_edit_axis_knobs(
function vpeol_3d_populate_transform (line 1610) | fn vpeol_3d_populate_transform(
FILE: tests/upgrade_level_file.rs
function test_upgrade_v1_to_v2 (line 4) | fn test_upgrade_v1_to_v2() {
Condensed preview — 58 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (438K chars).
[
{
"path": ".cargo/config.toml",
"chars": 316,
"preview": "[alias]\nexample2d = \"run --example example2d --features _example2d_full\"\nexample3d = \"run --example example3d --features"
},
{
"path": ".github/workflows/ci.yml",
"chars": 5836,
"preview": "name: CI\r\non:\r\n pull_request:\r\n push:\r\n branches: [main]\r\n\r\n# Sets permissions of the GITHUB_TOKEN to allow deploym"
},
{
"path": ".gitignore",
"chars": 227,
"preview": "/target\nCargo.lock\n\nassets/levels2d/*.yol\nassets/levels2d/*.yoli\n!assets/levels2d/example.yol\n\nassets/levels3d/*.yol\nass"
},
{
"path": "CHANGELOG.md",
"chars": 13595,
"preview": "# Changelog\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changel"
},
{
"path": "Cargo.toml",
"chars": 2614,
"preview": "[workspace]\nmembers = [\"macros\"]\n\n[workspace.package]\nedition = \"2024\"\nauthors = [\"IdanArye <idanarye@gmail.com>\", \"dexs"
},
{
"path": "LICENSE-APACHE",
"chars": 10847,
"preview": " Apache License\n Version 2.0, January 2004\n http"
},
{
"path": "LICENSE-MIT",
"chars": 1023,
"preview": "Permission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentati"
},
{
"path": "MIGRATION-GUIDES.md",
"chars": 12484,
"preview": "# Migrating to Yoleck 0.19\n\n## Using the new Bevy types\n\nBevy 0.13 introduces types for defining directions and planes, "
},
{
"path": "README.md",
"chars": 5062,
"preview": "[](https://github.com/idanarye/bevy-yolec"
},
{
"path": "assets/levels2d/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "assets/levels2d/example.yol",
"chars": 1531,
"preview": "[{\"format_version\":2,\"app_format_version\":1},{},[[{\"type\":\"Player\",\"name\":\"\"},{\"Vpeol2dPosition\":[-309.3874206542969,81."
},
{
"path": "assets/levels3d/.gitkeep",
"chars": 0,
"preview": ""
},
{
"path": "assets/levels3d/example.yol",
"chars": 819,
"preview": "[{\"format_version\":2,\"app_format_version\":0},{},[[{\"type\":\"Planet\",\"name\":\"\",\"uuid\":\"c8aa8fdd-5431-473c-8774-b069c95f794"
},
{
"path": "assets/levels_doors/entry.yol",
"chars": 435,
"preview": "[{\"format_version\":2,\"app_format_version\":0},{},[[{\"type\":\"FloatingText\",\"name\":\"\"},{\"TextContent\":{\"text\":\"Start Room\"}"
},
{
"path": "assets/levels_doors/index.yoli",
"chars": 124,
"preview": "[{\"format_version\":1},[{\"filename\":\"entry.yol\"},{\"filename\":\"room1.yol\"},{\"filename\":\"room2.yol\"},{\"filename\":\"room3.yol"
},
{
"path": "assets/levels_doors/room1.yol",
"chars": 811,
"preview": "[{\"format_version\":2,\"app_format_version\":0},{},[[{\"type\":\"Doorway\",\"name\":\"\"},{\"Doorway\":{\"marker\":\"s-1\",\"target_level\""
},
{
"path": "assets/levels_doors/room2.yol",
"chars": 449,
"preview": "[{\"format_version\":2,\"app_format_version\":0},{},[[{\"type\":\"Doorway\",\"name\":\"\"},{\"Doorway\":{\"marker\":\"1-2\",\"target_level\""
},
{
"path": "assets/levels_doors/room3.yol",
"chars": 445,
"preview": "[{\"format_version\":2,\"app_format_version\":0},{},[[{\"type\":\"Doorway\",\"name\":\"\"},{\"Doorway\":{\"marker\":\"1-3\",\"target_level\""
},
{
"path": "assets/these-assets-are-for-the-examples",
"chars": 0,
"preview": ""
},
{
"path": "examples/custom_camera3d.rs",
"chars": 9844,
"preview": "use std::path::Path;\n\nuse bevy::color::palettes::css;\nuse bevy::prelude::*;\nuse bevy_egui::{EguiContexts, EguiPlugin};\nu"
},
{
"path": "examples/doors_to_other_levels.rs",
"chars": 15251,
"preview": "use std::path::Path;\n\nuse bevy::color::palettes::css;\nuse bevy::math::Affine3A;\nuse bevy::platform::collections::HashSet"
},
{
"path": "examples/example2d.rs",
"chars": 20153,
"preview": "use std::path::Path;\n\nuse bevy::color::palettes::css;\nuse bevy::ecs::system::SystemState;\nuse bevy::mesh::Indices;\nuse b"
},
{
"path": "examples/example3d.rs",
"chars": 9572,
"preview": "use std::path::Path;\n\nuse bevy::prelude::*;\nuse bevy::{color::palettes::css, log::LogPlugin};\nuse bevy_egui::EguiPlugin;"
},
{
"path": "macros/Cargo.toml",
"chars": 331,
"preview": "[package]\nname = \"bevy-yoleck-macros\"\ndescription = \"Macros for bevy-yoleck\"\nversion = \"0.10.0\"\nedition.workspace = true"
},
{
"path": "macros/src/lib.rs",
"chars": 12087,
"preview": "use proc_macro2::TokenStream;\n\nuse quote::quote;\nuse syn::{Data, DeriveInput, Error, Field, Fields, LitStr, Token, Type}"
},
{
"path": "run-retrospective-crate-version-tagging.sh",
"chars": 220,
"preview": "#!/bin/bash\n\n(\n retrospective-crate-version-tagging detect \\\n --crate-name bevy-yoleck \\\n --changelog-p"
},
{
"path": "src/auto_edit.rs",
"chars": 22982,
"preview": "use bevy::prelude::*;\nuse bevy_egui::egui;\n\nuse crate::YoleckInternalSchedule;\nuse crate::entity_ref::resolve_entity_ref"
},
{
"path": "src/console.rs",
"chars": 7166,
"preview": "use bevy::log::BoxedLayer;\nuse bevy::log::tracing;\nuse bevy::log::tracing_subscriber;\nuse bevy::prelude::*;\nuse bevy_egu"
},
{
"path": "src/editing.rs",
"chars": 3683,
"preview": "use std::ops::{Deref, DerefMut};\n\nuse bevy::ecs::query::{QueryData, QueryFilter, QueryIter, QuerySingleError};\nuse bevy:"
},
{
"path": "src/editor.rs",
"chars": 29620,
"preview": "use std::any::TypeId;\nuse std::borrow::Cow;\nuse std::sync::Arc;\n\nuse bevy::ecs::system::SystemState;\nuse bevy::platform:"
},
{
"path": "src/editor_panels.rs",
"chars": 9335,
"preview": "use bevy::ecs::system::SystemId;\nuse bevy::prelude::*;\nuse bevy_egui::egui;\nuse std::ops::{Deref, DerefMut};\n\nuse crate:"
},
{
"path": "src/editor_window.rs",
"chars": 3291,
"preview": "use bevy::prelude::*;\nuse bevy::window::PrimaryWindow;\nuse bevy_egui::{EguiContext, PrimaryEguiContext, egui};\n\nuse crat"
},
{
"path": "src/entity_management.rs",
"chars": 11649,
"preview": "use std::collections::BTreeSet;\n\nuse bevy::asset::io::Reader;\nuse bevy::asset::{AssetLoader, LoadContext};\nuse bevy::pla"
},
{
"path": "src/entity_ref.rs",
"chars": 5100,
"preview": "use std::any::TypeId;\n\nuse bevy::ecs::component::Mutable;\nuse bevy::prelude::*;\nuse serde::{Deserialize, Serialize};\nuse"
},
{
"path": "src/entity_upgrading.rs",
"chars": 2379,
"preview": "use std::collections::BTreeMap;\n\nuse bevy::prelude::*;\n\nuse crate::YoleckRawLevel;\n\n/// Support upgrading of entities wh"
},
{
"path": "src/entity_uuid.rs",
"chars": 1134,
"preview": "use bevy::prelude::*;\n\nuse bevy::platform::collections::HashMap;\nuse uuid::Uuid;\n\n/// A UUID automatically added to enti"
},
{
"path": "src/errors.rs",
"chars": 685,
"preview": "use bevy::ecs::error::BevyError;\nuse uuid::Uuid;\n\n#[derive(thiserror::Error, Debug)]\npub(crate) enum YoleckAssetLoaderEr"
},
{
"path": "src/exclusive_systems.rs",
"chars": 5350,
"preview": "use std::collections::VecDeque;\n\nuse bevy::prelude::*;\n\npub(crate) struct YoleckExclusiveSystemsPlugin;\n\nimpl Plugin for"
},
{
"path": "src/knobs.rs",
"chars": 4476,
"preview": "use std::any::{Any, TypeId};\nuse std::hash::{BuildHasher, Hash};\n\nuse bevy::ecs::system::{EntityCommands, SystemParam};\n"
},
{
"path": "src/level_files_manager.rs",
"chars": 26926,
"preview": "use std::path::PathBuf;\nuse std::{fs, io};\n\nuse bevy::platform::collections::HashSet;\nuse bevy::prelude::*;\nuse bevy_egu"
},
{
"path": "src/level_files_upgrading.rs",
"chars": 1973,
"preview": "use bevy::prelude::*;\n\n/// Upgrade a level file to the most recent Yoleck level format\npub fn upgrade_level_file(mut lev"
},
{
"path": "src/level_index.rs",
"chars": 3676,
"preview": "use std::collections::BTreeSet;\nuse std::ops::Deref;\n\nuse bevy::asset::AssetLoader;\nuse bevy::prelude::*;\nuse bevy::refl"
},
{
"path": "src/lib.rs",
"chars": 27816,
"preview": "//! # Your Own Level Editor Creation Kit\n//!\n//! Yoleck is a crate for having a game built with the Bevy game engine act"
},
{
"path": "src/picking_helpers.rs",
"chars": 1340,
"preview": "use bevy::prelude::*;\nuse uuid::Uuid;\n\nuse crate::exclusive_systems::YoleckExclusiveSystemDirective;\nuse crate::prelude:"
},
{
"path": "src/populating.rs",
"chars": 5012,
"preview": "use std::ops::RangeFrom;\n\nuse bevy::ecs::query::{QueryData, QueryFilter};\nuse bevy::ecs::system::{EntityCommands, System"
},
{
"path": "src/specs_registration.rs",
"chars": 8196,
"preview": "use std::any::{Any, TypeId};\nuse std::marker::PhantomData;\n\nuse bevy::ecs::component::Mutable;\nuse bevy::ecs::system::En"
},
{
"path": "src/util.rs",
"chars": 1134,
"preview": "use bevy::prelude::*;\n\ntrait ContextSpecificResource: 'static + Sync + Send {\n fn inject_to_world(&mut self, world: &"
},
{
"path": "src/vpeol.rs",
"chars": 33640,
"preview": "//! # Viewport Editing Overlay - utilities for editing entities from a viewport.\n//!\n//! This module does not do much, b"
},
{
"path": "src/vpeol_2d.rs",
"chars": 24081,
"preview": "//! # Viewport Editing Overlay for 2D games.\n//!\n//! Use this module to implement simple 2D editing for 2D games.\n//!\n//"
},
{
"path": "src/vpeol_3d.rs",
"chars": 55724,
"preview": "//! # Viewport Editing Overlay for 3D games.\n//!\n//! Use this module to implement simple 3D editing for 3D games.\n//!\n//"
},
{
"path": "tests/upgrade_level_file.rs",
"chars": 1040,
"preview": "use bevy_yoleck::level_files_upgrading::upgrade_level_file;\n\n#[test]\nfn test_upgrade_v1_to_v2() {\n let orig_level = s"
}
]
// ... and 7 more files (download for full content)
About this extraction
This page contains the full source code of the idanarye/bevy-yoleck GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 58 files (411.6 KB), approximately 99.4k tokens, and a symbol index with 496 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.