use std::collections::VecDeque;
use std::fmt;
use std::net::Ipv4Addr;
use std::path::{Path, PathBuf};
use bevy::app::AppExit;
use bevy::input::InputSystems;
use bevy::prelude::*;
use bevy::remote::http::RemoteHttpPlugin;
use bevy::remote::{
BrpError, BrpResult, RemoteMethodSystemId, RemoteMethods, RemotePlugin, error_codes,
};
use bevy::render::view::window::screenshot::{Screenshot, ScreenshotCaptured, save_to_disk};
use bevy::ui::{ComputedNode, UiGlobalTransform, UiSystems};
use bevy::window::PrimaryWindow;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::AutomationId;
use crate::world::{ViewerPosition, WorldLoadingState};
pub const DEFAULT_REMOTE_PORT: u16 = 15702;
const DEFAULT_TIMEOUT_FRAMES: u32 = 600;
const SCREENSHOT_TIMEOUT_FRAMES: u32 = 600;
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UiTarget {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub entity: Option<u64>,
}
impl UiTarget {
pub fn text(text: impl Into<String>) -> Self {
Self {
text: Some(text.into()),
..Default::default()
}
}
pub fn id(id: impl Into<String>) -> Self {
Self {
id: Some(id.into()),
..Default::default()
}
}
fn is_empty(&self) -> bool {
self.text.is_none() && self.id.is_none() && self.entity.is_none()
}
fn matches(&self, element: &UiElement) -> bool {
self.text
.as_ref()
.is_none_or(|text| element.text.trim() == text.trim())
&& self
.id
.as_ref()
.is_none_or(|id| element.id.as_deref() == Some(id.as_str()))
&& self
.entity
.is_none_or(|bits| element.entity.to_bits() == bits)
}
}
impl fmt::Display for UiTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut parts = Vec::new();
if let Some(text) = &self.text {
parts.push(format!("text {text:?}"));
}
if let Some(id) = &self.id {
parts.push(format!("id {id:?}"));
}
if let Some(entity) = self.entity {
parts.push(format!("entity {entity}"));
}
write!(f, "{}", parts.join(", "))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "is", rename_all = "snake_case", deny_unknown_fields)]
pub enum AutomationCondition {
WorldReady,
UiVisible {
target: UiTarget,
},
UiHidden {
target: UiTarget,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum KeyAction {
#[default]
Tap,
Press,
Release,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "do", rename_all = "snake_case", deny_unknown_fields)]
pub enum AutomationStep {
WaitFrames {
frames: u32,
},
WaitUntil {
condition: AutomationCondition,
#[serde(default = "default_timeout_frames")]
timeout_frames: u32,
},
Key {
key: String,
#[serde(default)]
action: KeyAction,
},
UiActivate {
target: UiTarget,
},
UiList {
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<String>,
},
CameraTeleport {
position: [f32; 3],
},
CameraLookAt {
target: [f32; 3],
},
Screenshot {
name: String,
},
Quit,
}
fn default_timeout_frames() -> u32 {
DEFAULT_TIMEOUT_FRAMES
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AutomationScript(pub Vec<AutomationStep>);
impl AutomationScript {
pub fn from_json(json: &str) -> Result<Self, AutomationScriptError> {
serde_json::from_str(json).map_err(|error| AutomationScriptError::Parse(error.to_string()))
}
pub fn from_file(path: impl AsRef<Path>) -> Result<Self, AutomationScriptError> {
let path = path.as_ref();
let json = std::fs::read_to_string(path)
.map_err(|error| AutomationScriptError::Read(path.to_path_buf(), error.to_string()))?;
Self::from_json(&json)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AutomationScriptError {
Read(PathBuf, String),
Parse(String),
}
impl fmt::Display for AutomationScriptError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Read(path, error) => {
write!(
f,
"cannot read automation script {}: {error}",
path.display()
)
}
Self::Parse(error) => write!(f, "invalid automation script: {error}"),
}
}
}
impl std::error::Error for AutomationScriptError {}
#[derive(Debug, Clone, PartialEq)]
pub struct AutomationConfig {
pub output_dir: PathBuf,
pub script: Option<AutomationScript>,
pub remote_port: Option<u16>,
pub exit_when_script_ends: bool,
}
impl Default for AutomationConfig {
fn default() -> Self {
Self {
output_dir: PathBuf::from("automation"),
script: None,
remote_port: None,
exit_when_script_ends: true,
}
}
}
impl AutomationConfig {
pub fn with_script(mut self, script: AutomationScript) -> Self {
self.script = Some(script);
self
}
pub fn with_script_file(self, path: impl AsRef<Path>) -> Result<Self, AutomationScriptError> {
Ok(self.with_script(AutomationScript::from_file(path)?))
}
pub fn with_remote(mut self, port: u16) -> Self {
self.remote_port = Some(port);
self
}
pub fn with_output_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.output_dir = dir.into();
self
}
}
pub struct AutomationPlugin {
config: Option<AutomationConfig>,
}
impl AutomationPlugin {
pub fn enabled(config: AutomationConfig) -> Self {
Self {
config: Some(config),
}
}
pub fn disabled() -> Self {
Self { config: None }
}
pub fn is_enabled(&self) -> bool {
self.config.is_some()
}
}
impl Plugin for AutomationPlugin {
fn build(&self, app: &mut App) {
let Some(config) = &self.config else {
return;
};
app.insert_resource(AutomationState::new(config));
app.add_systems(
PreUpdate,
automation_system
.after(InputSystems)
.after(UiSystems::Focus),
);
if let Some(port) = config.remote_port {
if !app.is_plugin_added::<RemotePlugin>() {
app.add_plugins(RemotePlugin::default());
}
app.add_plugins(
RemoteHttpPlugin::default()
.with_address(Ipv4Addr::LOCALHOST)
.with_port(port),
);
let world = app.world_mut();
let status = world.register_system(remote_status);
let ui_list = world.register_system(remote_ui_list);
let run = world.register_system(remote_run);
let mut methods = world.resource_mut::<RemoteMethods>();
methods.insert("voxel.status", RemoteMethodSystemId::Instant(status));
methods.insert("voxel.ui_list", RemoteMethodSystemId::Instant(ui_list));
methods.insert("voxel.run", RemoteMethodSystemId::Instant(run));
}
}
}
enum Wait {
Frames(u32),
Until {
condition: AutomationCondition,
remaining: u32,
},
Screenshots {
remaining: u32,
},
}
enum Poll {
Ready,
Pending,
Failed(String),
}
#[derive(Resource)]
struct AutomationState {
output_dir: PathBuf,
exit_when_script_ends: bool,
frame: u64,
script: VecDeque<AutomationStep>,
script_active: bool,
next_step: usize,
wait: Option<Wait>,
queue: VecDeque<AutomationStep>,
keys_to_release: Vec<KeyCode>,
ui_to_release: Vec<Entity>,
pending_screenshots: usize,
report: Vec<Value>,
last_error: Option<String>,
}
impl AutomationState {
fn new(config: &AutomationConfig) -> Self {
let script: VecDeque<AutomationStep> = config
.script
.as_ref()
.map(|script| script.0.iter().cloned().collect())
.unwrap_or_default();
Self {
output_dir: config.output_dir.clone(),
exit_when_script_ends: config.exit_when_script_ends,
frame: 0,
script_active: config.script.is_some(),
script,
next_step: 0,
wait: None,
queue: VecDeque::new(),
keys_to_release: Vec::new(),
ui_to_release: Vec::new(),
pending_screenshots: 0,
report: Vec::new(),
last_error: None,
}
}
fn status(&self) -> Value {
json!({
"frame": self.frame,
"script_active": self.script_active,
"script_steps_remaining": self.script.len(),
"pending_screenshots": self.pending_screenshots,
"last_error": self.last_error,
"output_dir": self.output_dir.display().to_string(),
})
}
fn tick(&mut self, world: &mut World) {
self.frame += 1;
if let Some(mut input) = world.get_resource_mut::<ButtonInput<KeyCode>>() {
for key in self.keys_to_release.drain(..) {
input.release(key);
}
} else {
self.keys_to_release.clear();
}
for entity in self.ui_to_release.drain(..) {
if let Some(mut interaction) = world.get_mut::<Interaction>(entity)
&& *interaction == Interaction::Pressed
{
*interaction = Interaction::None;
}
}
while let Some(step) = self.queue.pop_front() {
if matches!(step, AutomationStep::Quit) {
world.write_message(AppExit::Success);
continue;
}
if let Err(error) = self.apply(world, &step) {
eprintln!("voxel-framework: automation: remote step failed: {error}");
self.last_error = Some(error);
}
}
self.run_script(world);
}
fn run_script(&mut self, world: &mut World) {
while self.script_active {
if let Some(mut wait) = self.wait.take() {
match self.poll(world, &mut wait) {
Poll::Ready => {}
Poll::Pending => {
self.wait = Some(wait);
return;
}
Poll::Failed(error) => {
self.fail(world, error);
return;
}
}
}
let Some(step) = self.script.pop_front() else {
self.finish(world, self.exit_when_script_ends);
return;
};
let index = self.next_step;
enum Kind {
Frames(u32),
Until(AutomationCondition, u32),
Quit,
Apply { screenshot: bool },
}
let kind = match &step {
AutomationStep::WaitFrames { frames } => Kind::Frames(*frames),
AutomationStep::WaitUntil {
condition,
timeout_frames,
} => Kind::Until(condition.clone(), *timeout_frames),
AutomationStep::Quit => Kind::Quit,
AutomationStep::Screenshot { .. } => Kind::Apply { screenshot: true },
_ => Kind::Apply { screenshot: false },
};
match kind {
Kind::Frames(frames) => {
self.record(index, &step, Ok(Value::Null));
self.next_step += 1;
if frames > 0 {
self.wait = Some(Wait::Frames(frames));
return;
}
}
Kind::Until(condition, remaining) => {
self.record(index, &step, Ok(Value::Null));
self.next_step += 1;
self.wait = Some(Wait::Until {
condition,
remaining,
});
}
Kind::Quit => {
if self.pending_screenshots > 0 {
self.script.push_front(step);
self.wait = Some(Wait::Screenshots {
remaining: SCREENSHOT_TIMEOUT_FRAMES,
});
continue;
}
self.record(index, &step, Ok(Value::Null));
self.next_step += 1;
self.finish(world, true);
return;
}
Kind::Apply { screenshot } => {
let result = self.apply(world, &step);
let failed = result.as_ref().err().cloned();
self.record(index, &step, result);
self.next_step += 1;
if let Some(error) = failed {
self.fail(world, error);
return;
}
self.wait = Some(if screenshot {
Wait::Screenshots {
remaining: SCREENSHOT_TIMEOUT_FRAMES,
}
} else {
Wait::Frames(1)
});
return;
}
}
}
}
fn poll(&mut self, world: &mut World, wait: &mut Wait) -> Poll {
match wait {
Wait::Frames(frames) => {
*frames = frames.saturating_sub(1);
if *frames == 0 {
Poll::Ready
} else {
Poll::Pending
}
}
Wait::Until {
condition,
remaining,
} => match condition_holds(world, condition) {
Ok(true) => Poll::Ready,
Ok(false) if *remaining == 0 => {
Poll::Failed(format!("timed out waiting for {condition:?}"))
}
Ok(false) => {
*remaining -= 1;
Poll::Pending
}
Err(error) => Poll::Failed(error),
},
Wait::Screenshots { remaining } => {
if self.pending_screenshots == 0 {
Poll::Ready
} else if *remaining == 0 {
Poll::Failed("timed out waiting for a screenshot to be captured".to_string())
} else {
*remaining -= 1;
Poll::Pending
}
}
}
}
fn record(&mut self, index: usize, step: &AutomationStep, result: Result<Value, String>) {
let step = serde_json::to_value(step).unwrap_or(Value::Null);
let entry = match result {
Ok(_) => json!({ "step": index, "command": step, "ok": true, "frame": self.frame }),
Err(error) => {
json!({ "step": index, "command": step, "ok": false, "error": error, "frame": self.frame })
}
};
self.report.push(entry);
}
fn fail(&mut self, world: &mut World, error: String) {
eprintln!(
"voxel-framework: automation: script failed at step {}: {error}",
self.next_step.saturating_sub(1)
);
self.last_error = Some(error);
self.script.clear();
self.finish(world, self.exit_when_script_ends);
}
fn finish(&mut self, world: &mut World, exit: bool) {
self.script_active = false;
self.wait = None;
let failed = self.last_error.is_some();
self.write_report();
if failed {
eprintln!("voxel-framework: automation: script ended with an error");
} else {
eprintln!(
"voxel-framework: automation: script finished ({} steps)",
self.next_step
);
}
if exit {
world.write_message(if failed {
AppExit::error()
} else {
AppExit::Success
});
}
}
fn write_report(&self) {
let report = json!({
"ok": self.last_error.is_none(),
"error": self.last_error,
"frames": self.frame,
"steps": self.report,
});
if let Err(error) = self.write_json("report", &report) {
eprintln!("voxel-framework: automation: {error}");
}
}
fn output_path(&self, name: &str, extension: &str) -> Result<PathBuf, String> {
let valid = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
&& !name.starts_with('.');
if !valid {
return Err(format!(
"invalid file name {name:?}: use letters, digits, '-', '_' and '.'"
));
}
std::fs::create_dir_all(&self.output_dir)
.map_err(|error| format!("cannot create {}: {error}", self.output_dir.display()))?;
Ok(self.output_dir.join(format!("{name}.{extension}")))
}
fn write_json(&self, name: &str, value: &Value) -> Result<PathBuf, String> {
let path = self.output_path(name, "json")?;
let text = serde_json::to_string_pretty(value).map_err(|error| error.to_string())?;
std::fs::write(&path, text)
.map_err(|error| format!("cannot write {}: {error}", path.display()))?;
Ok(path)
}
fn apply(&mut self, world: &mut World, step: &AutomationStep) -> Result<Value, String> {
match step {
AutomationStep::Key { key, action } => {
let code = parse_key(key).ok_or_else(|| format!("unknown key {key:?}"))?;
let mut input = world
.get_resource_mut::<ButtonInput<KeyCode>>()
.ok_or("the app has no keyboard input resource")?;
match action {
KeyAction::Tap => {
input.press(code);
self.keys_to_release.push(code);
}
KeyAction::Press => input.press(code),
KeyAction::Release => input.release(code),
}
Ok(Value::Null)
}
AutomationStep::UiActivate { target } => {
if target.is_empty() {
return Err("ui_activate needs a text, id or entity".to_string());
}
let elements = collect_ui(world);
let matches: Vec<&UiElement> = elements
.iter()
.filter(|element| element.interactive && element.visible)
.filter(|element| target.matches(element))
.collect();
let element = match matches.as_slice() {
[element] => *element,
[] => return Err(format!("no visible interactive UI element with {target}")),
many => {
return Err(format!(
"{} visible interactive UI elements match {target}; use an id or entity",
many.len()
));
}
};
let entity = element.entity;
if let Some(mut interaction) = world.get_mut::<Interaction>(entity) {
*interaction = Interaction::Pressed;
}
self.ui_to_release.push(entity);
Ok(json!({ "entity": entity.to_bits() }))
}
AutomationStep::UiList { name } => {
let list = ui_json(&collect_ui(world));
if let Some(name) = name {
self.write_json(name, &list)?;
}
Ok(list)
}
AutomationStep::CameraTeleport { position } => {
let position = Vec3::from_array(*position);
if !position.is_finite() {
return Err("camera_teleport needs a finite position".to_string());
}
let camera = camera_root(world)?;
let mut transform = world
.get_mut::<Transform>(camera)
.ok_or("the camera has no Transform")?;
transform.translation = position;
if let Some(mut viewer) = world.get_resource_mut::<ViewerPosition>() {
viewer.position = position;
}
Ok(Value::Null)
}
AutomationStep::CameraLookAt { target } => {
let target = Vec3::from_array(*target);
if !target.is_finite() {
return Err("camera_look_at needs a finite target".to_string());
}
let camera = camera_root(world)?;
let mut transform = world
.get_mut::<Transform>(camera)
.ok_or("the camera has no Transform")?;
let direction = target - transform.translation;
if direction.length_squared() < 1e-8 {
return Err("camera_look_at target is the camera position".to_string());
}
let up = if direction.normalize().dot(Vec3::Y).abs() > 0.999 {
Vec3::Z
} else {
Vec3::Y
};
transform.look_at(target, up);
Ok(Value::Null)
}
AutomationStep::Screenshot { name } => {
let path = self.output_path(name, "png")?;
let mut windows = world.query_filtered::<Entity, With<PrimaryWindow>>();
if windows.iter(world).next().is_none() {
return Err("screenshot needs a primary window".to_string());
}
self.pending_screenshots += 1;
world
.spawn(Screenshot::primary_window())
.observe(save_to_disk(path.clone()))
.observe(screenshot_done);
Ok(json!({ "path": path.display().to_string() }))
}
AutomationStep::WaitFrames { .. }
| AutomationStep::WaitUntil { .. }
| AutomationStep::Quit => Err("this step cannot be applied directly".to_string()),
}
}
}
fn screenshot_done(_: On<ScreenshotCaptured>, mut state: ResMut<AutomationState>) {
state.pending_screenshots = state.pending_screenshots.saturating_sub(1);
}
fn automation_system(world: &mut World) {
world.resource_scope(|world, mut state: Mut<AutomationState>| state.tick(world));
}
fn condition_holds(world: &mut World, condition: &AutomationCondition) -> Result<bool, String> {
match condition {
AutomationCondition::WorldReady => world
.get_resource::<WorldLoadingState>()
.map(|state| state.ready)
.ok_or_else(|| "world_ready needs LoadingPlugin".to_string()),
AutomationCondition::UiVisible { target } => {
if target.is_empty() {
return Err("ui_visible needs a text, id or entity".to_string());
}
Ok(collect_ui(world)
.iter()
.any(|element| element.visible && target.matches(element)))
}
AutomationCondition::UiHidden { target } => {
if target.is_empty() {
return Err("ui_hidden needs a text, id or entity".to_string());
}
Ok(!collect_ui(world)
.iter()
.any(|element| element.visible && target.matches(element)))
}
}
}
fn camera_root(world: &mut World) -> Result<Entity, String> {
let mut cameras = world.query_filtered::<Entity, With<Camera3d>>();
let mut entity = cameras.iter(world).next().ok_or("there is no 3D camera")?;
while let Some(parent) = world.get::<ChildOf>(entity) {
entity = parent.parent();
}
Ok(entity)
}
fn parse_key(name: &str) -> Option<KeyCode> {
let name = name.trim();
let lower = name.to_ascii_lowercase();
let short = lower
.strip_prefix("key")
.or_else(|| lower.strip_prefix("digit"))
.unwrap_or(&lower);
if short.len() == 1 {
let c = short.chars().next()?;
return Some(match c {
'a' => KeyCode::KeyA,
'b' => KeyCode::KeyB,
'c' => KeyCode::KeyC,
'd' => KeyCode::KeyD,
'e' => KeyCode::KeyE,
'f' => KeyCode::KeyF,
'g' => KeyCode::KeyG,
'h' => KeyCode::KeyH,
'i' => KeyCode::KeyI,
'j' => KeyCode::KeyJ,
'k' => KeyCode::KeyK,
'l' => KeyCode::KeyL,
'm' => KeyCode::KeyM,
'n' => KeyCode::KeyN,
'o' => KeyCode::KeyO,
'p' => KeyCode::KeyP,
'q' => KeyCode::KeyQ,
'r' => KeyCode::KeyR,
's' => KeyCode::KeyS,
't' => KeyCode::KeyT,
'u' => KeyCode::KeyU,
'v' => KeyCode::KeyV,
'w' => KeyCode::KeyW,
'x' => KeyCode::KeyX,
'y' => KeyCode::KeyY,
'z' => KeyCode::KeyZ,
'0' => KeyCode::Digit0,
'1' => KeyCode::Digit1,
'2' => KeyCode::Digit2,
'3' => KeyCode::Digit3,
'4' => KeyCode::Digit4,
'5' => KeyCode::Digit5,
'6' => KeyCode::Digit6,
'7' => KeyCode::Digit7,
'8' => KeyCode::Digit8,
'9' => KeyCode::Digit9,
_ => return None,
});
}
Some(match lower.as_str() {
"escape" | "esc" => KeyCode::Escape,
"space" => KeyCode::Space,
"enter" | "return" => KeyCode::Enter,
"tab" => KeyCode::Tab,
"backspace" => KeyCode::Backspace,
"shift" | "shiftleft" => KeyCode::ShiftLeft,
"shiftright" => KeyCode::ShiftRight,
"control" | "ctrl" | "controlleft" => KeyCode::ControlLeft,
"controlright" => KeyCode::ControlRight,
"alt" | "altleft" => KeyCode::AltLeft,
"altright" => KeyCode::AltRight,
"up" | "arrowup" => KeyCode::ArrowUp,
"down" | "arrowdown" => KeyCode::ArrowDown,
"left" | "arrowleft" => KeyCode::ArrowLeft,
"right" | "arrowright" => KeyCode::ArrowRight,
"f1" => KeyCode::F1,
"f2" => KeyCode::F2,
"f3" => KeyCode::F3,
"f4" => KeyCode::F4,
"f5" => KeyCode::F5,
"f6" => KeyCode::F6,
"f7" => KeyCode::F7,
"f8" => KeyCode::F8,
"f9" => KeyCode::F9,
"f10" => KeyCode::F10,
"f11" => KeyCode::F11,
"f12" => KeyCode::F12,
_ => return None,
})
}
struct UiElement {
entity: Entity,
id: Option<String>,
kind: &'static str,
text: String,
interactive: bool,
visible: bool,
rect: [f32; 4],
}
fn collect_ui(world: &mut World) -> Vec<UiElement> {
let mut nodes = world.query_filtered::<(
Entity,
Option<&AutomationId>,
Option<&Text>,
Has<Button>,
Has<Interaction>,
Option<&ComputedNode>,
Option<&UiGlobalTransform>,
Option<&InheritedVisibility>,
), With<Node>>();
let listed: Vec<_> = nodes
.iter(world)
.filter(|(_, id, text, is_button, ..)| *is_button || id.is_some() || text.is_some())
.map(
|(entity, id, text, is_button, interactive, computed, transform, visibility)| {
let rect = match (computed, transform) {
(Some(computed), Some(transform)) => {
let scale = computed.inverse_scale_factor;
let size = computed.size * scale;
let center = transform.translation * scale;
[
center.x - size.x * 0.5,
center.y - size.y * 0.5,
size.x,
size.y,
]
}
_ => [0.0; 4],
};
(
entity,
id.map(|id| id.0.clone()),
text.map(|text| text.0.clone()),
is_button,
interactive,
visibility.is_none_or(|visibility| visibility.get()),
rect,
)
},
)
.collect();
listed
.into_iter()
.map(
|(entity, id, own_text, is_button, interactive, visible, rect)| {
let text = own_text.clone().unwrap_or_else(|| {
let mut parts = Vec::new();
descendant_text(world, entity, &mut parts);
parts.join(" ")
});
let kind = if is_button {
"button"
} else if own_text.is_some() {
"text"
} else {
"node"
};
UiElement {
entity,
id,
kind,
text,
interactive,
visible,
rect,
}
},
)
.collect()
}
fn descendant_text(world: &World, entity: Entity, out: &mut Vec<String>) {
let Some(children) = world.get::<Children>(entity) else {
return;
};
for child in children.iter() {
if let Some(text) = world.get::<Text>(child) {
out.push(text.0.clone());
}
descendant_text(world, child, out);
}
}
fn ui_json(elements: &[UiElement]) -> Value {
Value::Array(
elements
.iter()
.map(|element| {
json!({
"entity": element.entity.to_bits(),
"id": element.id,
"kind": element.kind,
"text": element.text,
"interactive": element.interactive,
"visible": element.visible,
"rect": {
"x": element.rect[0],
"y": element.rect[1],
"width": element.rect[2],
"height": element.rect[3],
},
})
})
.collect(),
)
}
fn invalid_params(message: impl Into<String>) -> BrpError {
BrpError {
code: error_codes::INVALID_PARAMS,
message: message.into(),
data: None,
}
}
fn remote_status(In(_): In<Option<Value>>, state: Res<AutomationState>) -> BrpResult {
Ok(state.status())
}
fn remote_ui_list(In(_): In<Option<Value>>, world: &mut World) -> BrpResult {
Ok(ui_json(&collect_ui(world)))
}
fn remote_run(In(params): In<Option<Value>>, mut state: ResMut<AutomationState>) -> BrpResult {
let params =
params.ok_or_else(|| invalid_params("voxel.run needs a step or an array of steps"))?;
let steps: Vec<AutomationStep> = if params.is_array() {
serde_json::from_value(params)
} else {
serde_json::from_value(params).map(|step| vec![step])
}
.map_err(|error| invalid_params(format!("invalid step: {error}")))?;
if steps.iter().any(|step| {
matches!(
step,
AutomationStep::WaitFrames { .. } | AutomationStep::WaitUntil { .. }
)
}) {
return Err(invalid_params(
"wait steps are not available remotely; poll voxel.status instead",
));
}
let queued = steps.len();
state.queue.extend(steps);
Ok(json!({ "queued": queued, "frame": state.frame }))
}
#[cfg(test)]
mod tests {
use super::*;
use bevy::ecs::message::Messages;
use bevy::ecs::system::RunSystemOnce;
fn output_dir() -> tempfile::TempDir {
tempfile::tempdir().expect("temp dir")
}
fn config(dir: &tempfile::TempDir, json: &str) -> AutomationConfig {
AutomationConfig::default()
.with_output_dir(dir.path())
.with_script(AutomationScript::from_json(json).expect("valid script"))
}
fn build(config: AutomationConfig) -> App {
let mut app = App::new();
app.init_resource::<ButtonInput<KeyCode>>();
app.add_plugins(AutomationPlugin::enabled(config));
app
}
fn exits(app: &App) -> Vec<AppExit> {
app.world()
.resource::<Messages<AppExit>>()
.iter_current_update_messages()
.cloned()
.collect()
}
fn report(dir: &tempfile::TempDir) -> Value {
let text = std::fs::read_to_string(dir.path().join("report.json")).expect("report file");
serde_json::from_str(&text).expect("report is JSON")
}
#[test]
fn script_parses_every_step_kind() {
let script = AutomationScript::from_json(
r#"[
{"do": "wait_until", "condition": {"is": "world_ready"}},
{"do": "wait_until", "condition": {"is": "ui_visible", "target": {"text": "Resume"}}, "timeout_frames": 30},
{"do": "wait_until", "condition": {"is": "ui_hidden", "target": {"id": "menu"}}},
{"do": "wait_frames", "frames": 3},
{"do": "key", "key": "Escape"},
{"do": "key", "key": "W", "action": "press"},
{"do": "ui_activate", "target": {"entity": 42}},
{"do": "ui_list", "name": "ui"},
{"do": "ui_list"},
{"do": "camera_teleport", "position": [1.0, 2.0, 3.0]},
{"do": "camera_look_at", "target": [0.0, 0.0, 0.0]},
{"do": "screenshot", "name": "shot"},
{"do": "quit"}
]"#,
)
.expect("script should parse");
assert_eq!(script.0.len(), 13);
assert_eq!(
script.0[0],
AutomationStep::WaitUntil {
condition: AutomationCondition::WorldReady,
timeout_frames: 600,
}
);
assert_eq!(
script.0[5],
AutomationStep::Key {
key: "W".to_string(),
action: KeyAction::Press,
}
);
assert_eq!(script.0[12], AutomationStep::Quit);
let json = serde_json::to_string(&script).unwrap();
assert_eq!(AutomationScript::from_json(&json).unwrap(), script);
}
#[test]
fn script_rejects_unknown_commands_and_fields() {
for json in [
r#"[{"do": "fly"}]"#,
r#"[{"do": "key", "key": "W", "speed": 2}]"#,
r#"[{"do": "ui_activate", "target": {"label": "Resume"}}]"#,
r#"{"do": "quit"}"#,
"not json",
] {
assert!(
matches!(
AutomationScript::from_json(json),
Err(AutomationScriptError::Parse(_))
),
"{json} should be rejected"
);
}
}
#[test]
fn missing_script_file_is_a_read_error() {
let dir = output_dir();
let error = AutomationScript::from_file(dir.path().join("nope.json")).unwrap_err();
assert!(matches!(error, AutomationScriptError::Read(..)));
assert!(error.to_string().contains("nope.json"));
}
#[test]
fn key_names_accept_short_and_keycode_forms() {
assert_eq!(parse_key("Escape"), Some(KeyCode::Escape));
assert_eq!(parse_key("esc"), Some(KeyCode::Escape));
assert_eq!(parse_key("w"), Some(KeyCode::KeyW));
assert_eq!(parse_key("KeyW"), Some(KeyCode::KeyW));
assert_eq!(parse_key("1"), Some(KeyCode::Digit1));
assert_eq!(parse_key("Digit1"), Some(KeyCode::Digit1));
assert_eq!(parse_key("Up"), Some(KeyCode::ArrowUp));
assert_eq!(parse_key("F3"), Some(KeyCode::F3));
assert_eq!(parse_key("Hyper"), None);
assert_eq!(parse_key(""), None);
}
#[test]
fn disabled_plugin_adds_nothing() {
let mut app = App::new();
let plugin = AutomationPlugin::disabled();
assert!(!plugin.is_enabled());
app.add_plugins(plugin);
assert!(!app.world().contains_resource::<AutomationState>());
assert!(!app.world().contains_resource::<RemoteMethods>());
assert!(!app.is_plugin_added::<RemotePlugin>());
app.update();
}
#[test]
fn enabled_plugin_without_remote_opens_no_endpoint() {
let dir = output_dir();
let app = build(AutomationConfig::default().with_output_dir(dir.path()));
assert!(app.world().contains_resource::<AutomationState>());
assert!(!app.is_plugin_added::<RemotePlugin>());
assert!(!app.is_plugin_added::<RemoteHttpPlugin>());
}
#[test]
fn remote_endpoint_registers_the_voxel_methods() {
let dir = output_dir();
let mut app = App::new();
app.add_plugins(AutomationPlugin::enabled(
AutomationConfig::default()
.with_output_dir(dir.path())
.with_remote(DEFAULT_REMOTE_PORT),
));
assert!(app.is_plugin_added::<RemoteHttpPlugin>());
let methods = app.world().resource::<RemoteMethods>().methods();
for name in ["voxel.status", "voxel.ui_list", "voxel.run"] {
assert!(methods.iter().any(|m| m == name), "{name} is registered");
}
}
#[test]
fn script_runs_to_the_end_and_exits_successfully() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "wait_frames", "frames": 2}, {"do": "quit"}]"#,
));
app.update();
app.update();
assert!(exits(&app).is_empty(), "still waiting");
app.update();
assert_eq!(exits(&app), vec![AppExit::Success]);
let report = report(&dir);
assert_eq!(report["ok"], json!(true));
assert_eq!(report["steps"].as_array().unwrap().len(), 2);
}
#[test]
fn script_without_quit_exits_when_it_ends_unless_told_to_stay() {
let dir = output_dir();
let mut app = build(config(&dir, r#"[{"do": "wait_frames", "frames": 0}]"#));
app.update();
assert_eq!(exits(&app), vec![AppExit::Success]);
let dir = output_dir();
let mut stay = config(&dir, r#"[{"do": "wait_frames", "frames": 0}]"#);
stay.exit_when_script_ends = false;
let mut app = build(stay);
app.update();
assert!(exits(&app).is_empty());
assert_eq!(report(&dir)["ok"], json!(true));
}
#[test]
fn failing_step_stops_the_script_with_an_error_exit() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "key", "key": "NoSuchKey"}, {"do": "key", "key": "W"}]"#,
));
app.update();
assert_eq!(exits(&app), vec![AppExit::error()]);
let report = report(&dir);
assert_eq!(report["ok"], json!(false));
assert!(report["error"].as_str().unwrap().contains("NoSuchKey"));
assert_eq!(report["steps"].as_array().unwrap().len(), 1);
assert!(
!app.world()
.resource::<ButtonInput<KeyCode>>()
.pressed(KeyCode::KeyW)
);
}
#[test]
fn wait_until_times_out_as_a_failure() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "wait_until", "condition": {"is": "ui_visible", "target": {"text": "Never"}}, "timeout_frames": 2}]"#,
));
app.update();
app.update();
assert!(exits(&app).is_empty());
app.update();
assert_eq!(exits(&app), vec![AppExit::error()]);
assert!(
report(&dir)["error"]
.as_str()
.unwrap()
.contains("timed out")
);
}
#[test]
fn world_ready_condition_follows_the_loading_state() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "wait_until", "condition": {"is": "world_ready"}}, {"do": "quit"}]"#,
));
app.init_resource::<WorldLoadingState>();
app.update();
assert!(exits(&app).is_empty(), "the world is not ready yet");
app.world_mut().resource_mut::<WorldLoadingState>().ready = true;
app.update();
assert_eq!(exits(&app), vec![AppExit::Success]);
}
#[test]
fn key_tap_is_pressed_for_one_frame() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "key", "key": "Escape"}, {"do": "wait_frames", "frames": 5}]"#,
));
app.update();
let input = app.world().resource::<ButtonInput<KeyCode>>();
assert!(input.pressed(KeyCode::Escape));
assert!(input.just_pressed(KeyCode::Escape));
app.update();
let input = app.world().resource::<ButtonInput<KeyCode>>();
assert!(!input.pressed(KeyCode::Escape));
}
#[test]
fn key_press_holds_until_released() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[
{"do": "key", "key": "W", "action": "press"},
{"do": "wait_frames", "frames": 2},
{"do": "key", "key": "W", "action": "release"},
{"do": "wait_frames", "frames": 5}
]"#,
));
app.update();
app.update();
app.update();
assert!(
app.world()
.resource::<ButtonInput<KeyCode>>()
.pressed(KeyCode::KeyW)
);
app.update();
assert!(
!app.world()
.resource::<ButtonInput<KeyCode>>()
.pressed(KeyCode::KeyW)
);
}
fn spawn_menu(app: &mut App) -> (Entity, Entity) {
let resume = app
.world_mut()
.spawn((Button, Node::default(), InheritedVisibility::VISIBLE))
.with_child((
Text::new("Resume"),
Node::default(),
InheritedVisibility::VISIBLE,
))
.id();
let quit = app
.world_mut()
.spawn((
Button,
Node::default(),
InheritedVisibility::VISIBLE,
AutomationId::new("menu.quit"),
))
.with_child((
Text::new("Quit"),
Node::default(),
InheritedVisibility::VISIBLE,
))
.id();
app.world_mut().spawn((
Text::new("PAUSED"),
Node::default(),
InheritedVisibility::VISIBLE,
));
(resume, quit)
}
fn interaction(app: &App, entity: Entity) -> Interaction {
*app.world().get::<Interaction>(entity).unwrap()
}
#[test]
fn ui_list_reports_buttons_text_and_ids() {
let dir = output_dir();
let mut app = build(config(&dir, r#"[{"do": "ui_list", "name": "ui"}]"#));
let (resume, quit) = spawn_menu(&mut app);
app.update();
let text = std::fs::read_to_string(dir.path().join("ui.json")).expect("ui list saved");
let list: Value = serde_json::from_str(&text).unwrap();
let find = |entity: Entity| {
list.as_array()
.unwrap()
.iter()
.find(|e| e["entity"] == json!(entity.to_bits()))
.cloned()
.expect("element is listed")
};
let resume = find(resume);
assert_eq!(resume["kind"], json!("button"));
assert_eq!(resume["text"], json!("Resume"));
assert_eq!(resume["interactive"], json!(true));
assert_eq!(resume["id"], Value::Null);
assert_eq!(find(quit)["id"], json!("menu.quit"));
assert!(
list.as_array()
.unwrap()
.iter()
.any(|e| e["kind"] == json!("text") && e["text"] == json!("PAUSED"))
);
}
#[test]
fn ui_activate_presses_by_text_or_id_for_one_frame() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[
{"do": "ui_activate", "target": {"text": "Resume"}},
{"do": "ui_activate", "target": {"id": "menu.quit"}},
{"do": "wait_frames", "frames": 5}
]"#,
));
let (resume, quit) = spawn_menu(&mut app);
app.update();
assert_eq!(interaction(&app, resume), Interaction::Pressed);
assert_eq!(interaction(&app, quit), Interaction::None);
app.update();
assert_eq!(interaction(&app, resume), Interaction::None);
assert_eq!(interaction(&app, quit), Interaction::Pressed);
app.update();
assert_eq!(interaction(&app, quit), Interaction::None);
}
#[test]
fn ui_activate_fails_for_missing_ambiguous_or_hidden_targets() {
for (json, expected) in [
(
r#"[{"do": "ui_activate", "target": {"text": "Settings"}}]"#,
"no visible interactive",
),
(
r#"[{"do": "ui_activate", "target": {"text": "Same"}}]"#,
"2 visible interactive",
),
(
r#"[{"do": "ui_activate", "target": {"text": "Hidden"}}]"#,
"no visible interactive",
),
(
r#"[{"do": "ui_activate", "target": {"text": "PAUSED"}}]"#,
"no visible interactive",
),
(r#"[{"do": "ui_activate", "target": {}}]"#, "needs a text"),
] {
let dir = output_dir();
let mut app = build(config(&dir, json));
spawn_menu(&mut app);
for _ in 0..2 {
app.world_mut().spawn((
Button,
Node::default(),
Text::new("Same"),
InheritedVisibility::VISIBLE,
));
}
app.world_mut().spawn((
Button,
Node::default(),
Text::new("Hidden"),
InheritedVisibility::HIDDEN,
));
app.update();
assert_eq!(exits(&app), vec![AppExit::error()], "{json}");
let error = report(&dir)["error"].as_str().unwrap().to_string();
assert!(error.contains(expected), "{json}: {error}");
}
}
#[test]
fn ui_visibility_conditions_track_elements() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[
{"do": "wait_until", "condition": {"is": "ui_visible", "target": {"text": "Resume"}}},
{"do": "wait_until", "condition": {"is": "ui_hidden", "target": {"text": "Resume"}}},
{"do": "quit"}
]"#,
));
app.update();
assert!(exits(&app).is_empty(), "nothing is shown yet");
let (resume, _) = spawn_menu(&mut app);
app.update();
assert!(exits(&app).is_empty(), "now waiting for it to go away");
app.world_mut().despawn(resume);
app.update();
assert_eq!(exits(&app), vec![AppExit::Success]);
}
#[test]
fn camera_commands_move_the_camera_root_and_the_viewer() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[
{"do": "camera_teleport", "position": [10.0, 20.0, 30.0]},
{"do": "camera_look_at", "target": [10.0, 20.0, 0.0]},
{"do": "wait_frames", "frames": 5}
]"#,
));
app.init_resource::<ViewerPosition>();
let rig = app.world_mut().spawn(Transform::default()).id();
app.world_mut()
.spawn((Camera3d::default(), Transform::default(), ChildOf(rig)));
app.update();
let transform = *app.world().get::<Transform>(rig).unwrap();
assert_eq!(transform.translation, Vec3::new(10.0, 20.0, 30.0));
assert_eq!(
app.world().resource::<ViewerPosition>().position,
Vec3::new(10.0, 20.0, 30.0)
);
app.update();
let transform = *app.world().get::<Transform>(rig).unwrap();
assert!(transform.forward().distance(Vec3::NEG_Z) < 1e-4);
}
#[test]
fn camera_commands_fail_without_a_camera_or_with_bad_values() {
for json in [
r#"[{"do": "camera_teleport", "position": [0.0, 0.0, 0.0]}]"#,
r#"[{"do": "camera_look_at", "target": [0.0, 1.0, 0.0]}]"#,
] {
let dir = output_dir();
let mut app = build(config(&dir, json));
app.update();
assert_eq!(exits(&app), vec![AppExit::error()], "{json}");
assert!(
report(&dir)["error"]
.as_str()
.unwrap()
.contains("no 3D camera")
);
}
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "camera_look_at", "target": [0.0, 0.0, 0.0]}]"#,
));
app.world_mut()
.spawn((Camera3d::default(), Transform::default()));
app.update();
assert_eq!(exits(&app), vec![AppExit::error()]);
}
#[test]
fn screenshot_needs_a_window_and_a_safe_name() {
let dir = output_dir();
let mut app = build(config(&dir, r#"[{"do": "screenshot", "name": "shot"}]"#));
app.update();
assert_eq!(exits(&app), vec![AppExit::error()]);
assert!(
report(&dir)["error"]
.as_str()
.unwrap()
.contains("primary window")
);
for name in ["../escape", "a/b", ".hidden", ""] {
let dir = output_dir();
let json = serde_json::to_string(&json!([{"do": "screenshot", "name": name}])).unwrap();
let mut app = build(config(&dir, &json));
app.world_mut().spawn((Window::default(), PrimaryWindow));
app.update();
assert_eq!(exits(&app), vec![AppExit::error()], "{name:?}");
assert!(
report(&dir)["error"]
.as_str()
.unwrap()
.contains("invalid file name")
);
}
}
#[test]
fn screenshot_request_is_spawned_and_awaited() {
let dir = output_dir();
let mut app = build(config(
&dir,
r#"[{"do": "screenshot", "name": "shot"}, {"do": "quit"}]"#,
));
app.world_mut().spawn((Window::default(), PrimaryWindow));
app.update();
app.update();
assert!(exits(&app).is_empty());
let world = app.world_mut();
assert_eq!(world.query::<&Screenshot>().iter(world).count(), 1);
assert_eq!(world.resource::<AutomationState>().pending_screenshots, 1);
}
fn remote_app(dir: &tempfile::TempDir) -> App {
build(AutomationConfig::default().with_output_dir(dir.path()))
}
#[test]
fn remote_status_reports_the_frame() {
let dir = output_dir();
let mut app = remote_app(&dir);
app.update();
app.update();
let status = app
.world_mut()
.run_system_once_with(remote_status, None)
.unwrap()
.unwrap();
assert_eq!(status["frame"], json!(2));
assert_eq!(status["script_active"], json!(false));
}
#[test]
fn remote_run_queues_steps_for_the_next_frame() {
let dir = output_dir();
let mut app = remote_app(&dir);
let (resume, _) = spawn_menu(&mut app);
app.update();
let reply = app
.world_mut()
.run_system_once_with(
remote_run,
Some(json!([
{"do": "key", "key": "Escape"},
{"do": "ui_activate", "target": {"text": "Resume"}}
])),
)
.unwrap()
.unwrap();
assert_eq!(reply["queued"], json!(2));
assert!(
!app.world()
.resource::<ButtonInput<KeyCode>>()
.pressed(KeyCode::Escape),
"nothing is applied until the next frame"
);
app.update();
assert!(
app.world()
.resource::<ButtonInput<KeyCode>>()
.just_pressed(KeyCode::Escape)
);
assert_eq!(interaction(&app, resume), Interaction::Pressed);
app.world_mut()
.run_system_once_with(remote_run, Some(json!({"do": "quit"})))
.unwrap()
.unwrap();
app.update();
assert_eq!(exits(&app), vec![AppExit::Success]);
}
#[test]
fn remote_run_rejects_bad_input_and_wait_steps() {
let dir = output_dir();
let mut app = remote_app(&dir);
for params in [
None,
Some(json!({"do": "fly"})),
Some(json!({"do": "wait_frames", "frames": 3})),
Some(
json!([{"do": "key", "key": "W"}, {"do": "wait_until", "condition": {"is": "world_ready"}}]),
),
] {
let error = app
.world_mut()
.run_system_once_with(remote_run, params.clone())
.unwrap()
.unwrap_err();
assert_eq!(error.code, error_codes::INVALID_PARAMS, "{params:?}");
}
assert!(app.world().resource::<AutomationState>().queue.is_empty());
}
#[test]
fn remote_step_failure_is_reported_in_status_without_exiting() {
let dir = output_dir();
let mut app = remote_app(&dir);
app.world_mut()
.run_system_once_with(remote_run, Some(json!({"do": "key", "key": "NoSuchKey"})))
.unwrap()
.unwrap();
app.update();
assert!(exits(&app).is_empty());
let status = app
.world_mut()
.run_system_once_with(remote_status, None)
.unwrap()
.unwrap();
assert!(status["last_error"].as_str().unwrap().contains("NoSuchKey"));
}
#[test]
fn remote_ui_list_matches_the_ui() {
let dir = output_dir();
let mut app = remote_app(&dir);
spawn_menu(&mut app);
let list = app
.world_mut()
.run_system_once_with(remote_ui_list, None)
.unwrap()
.unwrap();
let texts: Vec<&str> = list
.as_array()
.unwrap()
.iter()
.filter(|e| e["kind"] == json!("button"))
.map(|e| e["text"].as_str().unwrap())
.collect();
assert!(texts.contains(&"Resume") && texts.contains(&"Quit"));
}
}