Attach Bevy's Handles/Entities statically to Types.

Overview

Easily attach bevy's Handles/Entities statically to types on startup and get them in any system, without using Resources.

It's just a little less clutter, and a bit more descriptive: e.g. Image::get_icon() would return a weak clone of the Handle set with Image::set_icon(img_handle). The setter can only be used once! This is only useful if you're sure these Handles/Entities will never change (and are always available)! For a more general use case, see type_cell.

Overview

use bevy_cell::*;
// setup cells
handle_cell!{Image: handle_a;}
entity_cell!{entity_a}
// on startup
Image::set_handle_a(img_handle);
Entity::set_entity_a(entity);
// in any system
Image::get_handle_a();
Entity::get_entity_a();

The macro also accepts multiple definitions at once:

handle_cell!{
    Image: image_a, image_b, image_c;
    Mesh: mesh_a, mesh_b;
}
handle_cell!{ @Vec
    Image: image_vec_a, image_vec_b, image_vec_c;
    Mesh: mesh_vec_a, mesh_vec_b;
}
entity_cell!{
    entity_a, entity_b, entity_c
}

For Vec/HashMaps:

handle_cell!{@Vec Image: numbers;}
handle_cell!{@HashMap<K> Image: numbers_id;}
entity_cell!{@Vec slots}
entity_cell!{@HashMap<K> slots_id}
// on startup
Image::set_numbers(img_handle_vec);
Image::set_numbers_id(img_handle_map);
Entity::set_slots(entity_vec);
Entity::set_slots_id(entity_map);
// in any system
Image::get_numbers(index);
Image::get_numbers_id(key);
Entity::get_slots(index);
Entity::get_slots_id(key);

Simple Example

use bevy_cell::*;
use bevy::prelude::*;

handle_cell!{Image: number;}
entity_cell!{slot}

fn startup (
    mut cmd: Commands,
    assets: Res<AssetServer>
){
    cmd.spawn(Camera2dBundle::default());
    // set Handles/Entities once on startup
    Image::set_number(assets.load("num_005.png"));
    Entity::set_slot(cmd.spawn(SpriteBundle{
        texture: assets.load("num_000.png"),
        ..default()
    }).id());
}

fn update (
    mut timer: ResMut<ChangeTimer>,
    time: Res<Time>,
    mut qu: Query<&mut Handle<Image>>
){
    timer.0.tick(time.delta());
    if timer.0.just_finished() {
        // get Handles/Entities anywhere
        *qu.get_mut(Entity::get_slot()).unwrap() = Image::get_number(); 
    }
}

#[derive(Resource)]
struct ChangeTimer(Timer);

fn main () {
    let mut app = App::new();
    app
    .add_plugins(DefaultPlugins)
    .add_systems(Startup,startup)
    .add_systems(Update,update)
    .insert_resource(ChangeTimer(Timer::from_seconds(1.,TimerMode::Once)))
    .run();
}

Example, using some experimental features

In handle_cell:
@Vec: save a Vec of handles, instead of just one
#load: the setter will load multiple assets from the folder, which are numbered.
#random: include a getter, which returns a random Handle of this Vec.

use bevy_cell::*;
use bevy::prelude::*;

handle_cell!{@Vec #load #random Image: numbers;}
entity_cell!{slot}

fn startup (
    mut cmd: Commands,
    assets: Res<AssetServer>
){
    cmd.spawn(Camera2dBundle::default());
    // loads num_000.png - num_009.png and attach it as Vec<Handle<Image>>
    // into the Image type. Image::get_numbers(index) returns the Handle now.
    Image::set_numbers((&assets,"num",0..=9,"png").into());
    // Saves the spawned Entity into the Entity type. Entity::get_slot()
    // returns this entity now anywhere.
    Entity::set_slot(cmd.spawn(SpriteBundle{
        texture: Image::get_numbers_random(),
        ..default()
    }).id());
}

fn update (
    mut timer: ResMut<ChangeTimer>,
    time: Res<Time>,
    mut qu: Query<&mut Handle<Image>>
){
    timer.0.tick(time.delta());
    if timer.0.just_finished() {
        // Change the Handle<Image> of the Slot-Entities to a random number-image.
        *qu.get_mut(Entity::get_slot()).unwrap() = Image::get_numbers_random(); 
    }
}

#[derive(Resource)]
struct ChangeTimer(Timer);

fn main () {
    let mut app = App::new();
    app
    .add_plugins(DefaultPlugins)
    .add_systems(Startup,startup)
    .add_systems(Update,update)
    .insert_resource(ChangeTimer(Timer::from_seconds(1.,TimerMode::Repeating)))
    .run();
}
You might also like...
🏷️ Markers for Bevy ECS Entities

Bevy ECS Markers Adds the support for marking entites and fetching them in queries Example View the whole example here #[derive(EntityMarker)] enum Pl

An opinionated 2D sparse grid made for use with Bevy. For storing and querying entities

bevy_sparse_grid_2d An opinionated 2D sparse grid made for use with Bevy. For storing and querying entities. Personally, I'm using it for simple stupi

Bevy Entities are nice. Objects are better!

🌴 Moonshine Object An extension to Bevy which provides an ergonomic interface for managing complex Entity hierarchies. Entities are nice. Objects are

Allows conversion between ndarray's types and image's types
Allows conversion between ndarray's types and image's types

ndarray-image Allows conversion between ndarray's types and image's types Deprecated WARNING: This crate is currently deprecated in favor of https://g

A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely 🦀 📈🚀
A rust drawing library for high quality data plotting for both WASM and native, statically and realtimely 🦀 📈🚀

Plotters - A Rust drawing library focus on data plotting for both WASM and native applications 🦀 📈 🚀 Plotters is drawing library designed for rende

Orion lang is a lispy programming language that is strongly and statically typed.
Orion lang is a lispy programming language that is strongly and statically typed.

Orion Orion is a lisp inspired statically typed programming language written in Rust Install To install orion you can either: Download binary from the

EXPERIMENTAL: Bitcoin Core Prometheus exporter based on User-Space, Statically Defined Tracing and eBPF.

bitcoind-observer An experimental Prometheus metric exporter for Bitcoin Core based on Userspace, Statically Defined Tracing and eBPF. This demo is ba

A statically-typed, interpreted programming language, with generics and type inference

Glide A programming language. Currently, this includes: Static typing Generics, with monomorphization Type inference on function calls func identityT

Statically sized matrix using a definition with const generics

Statically sized matrix using a definition with const generics

Statically allocated, runtime initialized cell.

static-cell Statically allocated, initialized at runtime cell. StaticCell provides a no-std-compatible, no-alloc way to reserve memory at compile time

A statically typed language that can deeply improve the Python ecosystem

The Erg Programming Language This is the main source code repository for Erg. This contains the compiler and documentation. 日本語 | 简体中文 | 繁體中文 Erg can

Statically verified Rust struct field names as strings.

field Statically verified struct field names as strings. See the documentation for more details. Installation Add the following to your Cargo manifest

The compiler for Gera, a statically typed and garbage collected programming language.

Gera The compiler for Gera, a satically typed and garbage collected programming language. Currently WIP (Work in progress). Progress This is a rough o

A parser combinator that is fully statically dispatched and supports both sync/async.

XParse A parser combinator that is fully statically dispatched and supports both sync & async parsing. How to use An example of a very simple JSON par

⚡🦀 🧨 make your rust types fit DynamoDB and visa versa

🦀 🧨 dynomite dynomite makes DynamoDB fit your types (and visa versa) Overview Goals ⚡ make writing dynamodb applications in rust a productive experi

Array helpers for Rust's Vector and String types

array_tool Array helpers for Rust. Some of the most common methods you would use on Arrays made available on Vectors. Polymorphic implementations for

Generic array types in Rust

generic-array This crate implements generic array types for Rust. Requires minumum Rust version of 1.36.0, or 1.41.0 for From[T; N] implementations

Rust crate to extend io::Read & io::Write types with progress callbacks

progress-streams Rust crate to provide progress callbacks for types which implement io::Read or io::Write. Examples Reader extern crate progress_strea

A lean, minimal, and stable set of types for color interoperation between crates in Rust.

This library provides a lean, minimal, and stable set of types for color interoperation between crates in Rust. Its goal is to serve the same function that mint provides for (linear algebra) math types.

Owner
Dekirisu
🦀 a learning rustacean
Dekirisu
An opinionated 2D sparse grid made for use with Bevy. For storing and querying entities

bevy_sparse_grid_2d An opinionated 2D sparse grid made for use with Bevy. For storing and querying entities. Personally, I'm using it for simple stupi

Johan Klokkhammer Helsing 5 Feb 26, 2023
Bevy Entities are nice. Objects are better!

?? Moonshine Object An extension to Bevy which provides an ergonomic interface for managing complex Entity hierarchies. Entities are nice. Objects are

null 7 May 7, 2024
Terminal UI implementation and types for the Dark Forest game

dark-forest.rs Terminal UI implementation and types for the Dark Forest game Development We use the standard Rust toolchain cargo check

Georgios Konstantopoulos 63 Nov 12, 2022
🍖A WGPU graphics pipeline, along with simple types used to marshal data to the GPU

renderling ?? This library is a collection of WGPU render pipelines. Shaders are written in GLSL. shaderc is used to compile shaders to SPIR-V. Defini

Schell Carl Scivally 5 Dec 20, 2022
Bevy plugin to simulate and preview different types of Color Blindness.

Bevy Color Blindness Simulation Bevy plugin to simulate and preview different types of Color Blindness. This lets you ensure that your game is accessi

annie 29 Nov 22, 2022
Simple stupid noise primitives for WGSL and Rust (glam/bevy types)

noisy_bevy Simple stupid noise primitives for glam types (Vec2, Vec3) and wgsl. Main motivations are: ergonomic usage with Bevy same results on rust a

Johan Klokkhammer Helsing 10 Dec 10, 2022
Serialize/DeSerialize for Rust built-in types and user defined types (complex struct types)

Serialize/DeSerialize for Rust built-in types and user defined types (complex struct types)

null 2 May 3, 2022
A 3d gizmo for transforming entities in Bevy.

Bevy Transform Gizmo This Bevy plugin adds a transform gizmo to entities in the scene, allowing you to drag and rotate meshes with your mouse. Demo.mp

Foresight 86 Jan 4, 2023
Read-optimized cache of Cardano on-chain entities

Read-optimized cache of Cardano on-chain entities Intro Scrolls is a tool for building and maintaining read-optimized collections of Cardano's on-chai

TxPipe 58 Dec 2, 2022
Command-line tool to make Rust source code entities from Postgres tables.

pg2rs Command-line tool to make Rust source code entities from Postgres tables. Generates: enums structs which can be then used like mod structs; use

Stanislav 10 May 20, 2022