一个用于 Bevy 的反应式 UI 框架
Quill is a UI framework for the Bevy game engine. It's meant to provide a simple API for constructing reactive user interfaces, similar to frameworks like React and Solid, but built on a foundation of Bevy ECS state management.
Quill is an experimental library which borrows ideas from a number of popular UI frameworks, including React.js, Solid.js, Dioxus, and Xilem. However, the way these ideas are implemented is quite different, owing to the need to build on the foundations of Bevy ECS.
Quill is relatively unopinionated about styling, layout or ECS hierarchies - you can use it to
build a traditional 2D game UI, gizmo-like overlays in 3D, or reactive scenes. However, Quill
comes with a separate crate, bevy_quill_obsidian which provides a set of opininated widgets for
building game editors.
:warning: Quill currently requires the unstable Rust feature
impl_trait_in_assoc_type. This requirement will go away once the feature has been stabilized, which is scheduled to happen sometime before the end of 2024.
:warning: Quill is currently in early development, and is likely to change as it evolves.
For now, you can run the examples. The "complex" example shows off multiple features of the library:
cargo run --example complexuse_resource() that hook into Bevy's change detection framework.View trait.To create a basic widget, start by creating a struct which implements the ViewTemplate trait.
This trait has one method, create(), which takes a context (Cx) and returns a View.
/// A view template
struct MyWidget;
impl ViewTempate for MyWidget {
type View = impl View;
fn create(cx: &mut Cx) -> Self::View {
// Access data in a resource
let counter = cx.use_resource::();
Element::::new().children((
format!("The count is: {}", counter.count),
))
}
}To actually display this widget, you'll need to set up a few things:
QuillPlugin in your app's plugins.Counter resource.The view root is an ECS entity which represents the root of the UI hierarchy. Note that there are actually two hierarchies, the "view hierarchy" which is the tree of templates and reactive objects, and the "display hierarchy", which are the actual Bevy entities that get rendered on the screen. You only need to worry about the former, since the display hierarchy is automatically constructed.
To spawn a root for the MyWidget template, use Bevy commands in a setup system:
commands.spawn(MyWidget.to_root());Quill manages views and templates on three different levels:
React.js, a ViewTemplate is the equivalent of a React Component.Every ViewTemplate has a method called create which is called when the template is first
spawned, and which is called again each time the display needs to update. It's important to
understand how create() is called, as this is the key to working with Quill:
create() is typically called many times, which means that any code inside of create needs to
be written in a way that is repeatable. Fortunately, the Cx object has lots of methods to help
with this: for example, if you want to write some code that only runs once, or only runs under
certain situations, you can call cx.create_effect().create() is reactive, meaning that it will be run again whenever one of its dependencies change.
For example, when you access a Bevy resource or component, it automatically adds that resource or
component to a tracking list. If some other function later modifies that resource or component,
it will trigger a reaction, which will cause create to run again.It's important to write the create() method in a way that doesn't leak memory or resources.
For example, it would be a mistake to write a create() method that calls material_assets.add()
directly, since this would add a new material every update, returning a new handle. Instead, you can
wrap the material initialization in a call to cx.create_memo(), which will allow you to preserve
the material handle between invocations.
As a general rule, you should write your templates in a "mostly functional" style, minimizing
side effects. When you do need side effects, there are special methods available like .insert()
or .create_mutable() to help you out.
The return value from create is an object that implements the View trait. Views have a more
complicated lifecycle that involves methods such as build(), rebuild() and raze(), but most
of the time you won't need to worry about these.
Typically you won't need to write your own implementations of View, as these have already
been provided. The most important of these is the Element type, which creates a single display
node entity. Elements have three aspects:
The children of an element are also views, defined using View objects. These are constructed by
the parent and inserted as children of the display node using the standard Bevy parent/child
relations.
"Effects" are anything that add or modify an entity's ECS components, such as:
bevy_mod_picking event handlers.Children and effects are added using a builder pattern, as in the following example:
Element::::new()
.style(style_panel)
.children((
"Hello, ",
"world!",
))The children() method accepts either a single view or a tuple of views. In this case, we're passing
plain text strings. Because the View trait has an implementation for &str, these strings can
be displayed as views, and will construct the appropriate bevy_ui Text nodes.
Note that ViewTemplates also implement View, so you can freely mix both templates and views
when defining children.
In the above example, the .style() method adds a "style effect" - an effect which initializes the
style components of the entity.
The .style() method is an example of a static effect, an effect which is only applied once
when the element is first created. There are also dynamic effects which can be applied multiple
times. Dynamic effects typically take a list of dependencies, and only re-run the effect when the
dependencies change. For example, here's a style effect which displays a "focus rectangle" around
a checkbox, but only when the "focus" flag (as determined by the accessiibility Focus resource)
is set to true:
.style_dyn(
// This closure only runs when 'focused' changes.
|focused, sb| {
if focused {
sb.outline_color(colors::FOCUS)
.outline_offset(1.0)
.width(2.0);
} else {
sb.outline_color(Option::::None);
}
},
focused,
)Another frequently-used effect is .insert() and it's dynamic counterpart, .insert_dyn(), which
inserts an ECS component. There's also a variation, .insert_if() which inserts a component when
the condition is true, and removes it when it's false - handy for marker components like Disabled.
The .insert() method is frequently used for inserting bevy_mod_picking event handlers.
CondThe Cond (short for "conditional") view takes a conditional expression, and two child views, one
which is built when the condition is true, the other when the condition is false.
/// Widget that displays whether the count is even or odd.
struct EvenOrOdd;
impl ViewTempate for EvenOrOdd {
type View = impl View;
fn create(cx: &mut Cx) -> Self::View {
let counter = cx.use_resource::();
Element::new().children((
"The count is: ",
Cond::new(counter.count & 1 == 0, "even", "odd"),
))
}
}Note: It's perfectly OK to use a regular if statement or match for conditional views, however
there is a limitation, which is that the result type has to be the same for all branches. Cond
doesn't have this limitation, the true and false branches can be different types. Internally,
Cond tears down the previous branch and initializes the new branch whenever the condition variable
changes.
Often the "false" branch of a Cond will be the empty view, (), which renders nothing and
creates no entities.
SwitchYou can select from multiple views using Switch. This works great with Bevy game states!
let state = *cx.use_resource::>().get();
Switch::new(state)
.case(EditorState::Realm, EditModeRealmControls)
.case(EditorState::Terrain, EditModeTerrainControls)
.case(EditorState::Scenery, EditModeSceneryControls)
.case(EditorState::Meta, EditModeMetadataControls)
.case(EditorState::Play, EditModePlayControls)ForFor::each() takes a list of items, and a callback which builds a View for each item:
struct EventLog;
impl ViewTempate for EventLog {
type View = impl View;
fn create(cx: &mut Cx) -> Self::View {
let log = cx.use_resource::();
Element::new()
.children(For::each(&log.0, |item| {
Element::new()
.styled(STYLE_LOG_ENTRY.clone())
.children((item.to_owned(), "00:00:00"))
}).with_fallback("No items")),
}
}During updates, the For view compares the list of items with the previous list and computes
a diff. Only items which have actually changed (insertions, deletions and mutations) are
rebuilt. There are three different variations of the For construct, which differ in how they
handle comparisons between items:
For::each() requires that the array elements implement PartialEq.For::each_cmp() takes an additional comparator argument which is used to compare the items.For::index() doesn't compare items, but instead uses the array index as a key. This version
is less efficient, since an item insertion or deletion will require re-building all of the
child views.Normally a ViewTemplate returns a single View. If you want to return multiple views,
use a tuple:
(
"Hello, ",
"World!"
)This works because tuples of views are also views.
To despawn a Quill view hierarchy, simply call .despawn() on the root entity. Do not call
.despawn_recursive() as this will panic. The reason is because the Quill view hierarchy is
more complex than just simple parent/child relationships, and relies on Bevy component hooks
to do it's interna
暂无开放 Issues,或尚未同步最近议题。