Skip to content

Commit

Permalink
Fix waymarks and wasm.
Browse files Browse the repository at this point in the history
We are good to go.
  • Loading branch information
spectria-limina committed Dec 3, 2024
1 parent b08e757 commit 034c2ae
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 72 deletions.
24 changes: 12 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
</head>
<body>
<main>
<canvas id="stratmat" data-stramat-asset-root="/static/app/"></canvas>
<canvas id="stratmat" style="height: 100% !important; width: 100% !important"
data-stratmat-log-filter="stratmat::waymark=debug"
data-stratmat-asset-root="/static/app/assets/"></canvas>
</canvas>
</main>
<script type="module">
import init from "/static/app/stratmat.js"
Expand Down
17 changes: 12 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ fn start(args: Args, primary_window: Window) -> eyre::Result<()> {
primary_window: Some(primary_window),
..default()
})
.set(log_plugin),
.set(log_plugin)
.set(AssetPlugin {
meta_check: bevy::asset::AssetMetaCheck::Never,
..default()
}),
)
.add_plugins(EguiPlugin)
.add_plugins(Shape2dPlugin::default())
Expand Down Expand Up @@ -157,25 +161,28 @@ fn main() -> eyre::Result<()> {
fn main() -> Result<(), JsValue> {
use convert_case::{Case, Casing};
use web_sys::console;
console::log_1(&"stratmat init: initializing...".into());

let selector = option_env!("STRATMAT_CANVAS").unwrap_or_else(|| "#stratmat");
let matches = web_sys::window()
.unwrap()
.document()
.unwrap()
.query_selector_all(selector)?;

console::log_1(&format!("stratmat init: found {} canvases", matches.length()).into());
#[cfg(debug_assertions)]
console::log_1(&format!("stratmat init: found {} canvas(es)", matches.length()).into());
let args = match matches.length() {
0 => Args::parse(),
1 => {
console::log_1(&"stratmat init: loading arguments from data attributes".into());
let canvas: web_sys::HtmlCanvasElement =
matches.get(0).unwrap().dyn_into().map_err(|elem| {
format!("stratmat requires a <canvas>, not a <{}>", elem.node_name())
})?;
let dataset = canvas.dataset();
let keys = js_sys::Reflect::own_keys(&dataset)?;
let mut args = vec![];
// Arg 0 is the "process name"
let mut args = vec!["".to_owned()];
for key in keys.iter() {
if let Some(name) = key
.as_string()
Expand All @@ -188,7 +195,7 @@ fn main() -> Result<(), JsValue> {
}
}
console::log_1(&format!("stratmat init: args: {:?}", args).into());
Args::parse_from(args)
Args::try_parse_from(args).map_err(|e| format!("invalid arguments: {e}"))?
}
_ => {
return Err("multiple elements match selector '{CANVAS}'".into());
Expand Down
51 changes: 18 additions & 33 deletions src/waymark/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ pub struct PresetEntry {
#[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)]
#[derive(Component, Reflect, Serialize, Deserialize)]
#[derive(IntEnum, Sequence)]
#[require(Transform, Visibility, Collider, CollidingEntities, AlphaScale)]
pub enum Waymark {
A = 0,
B = 1,
Expand Down Expand Up @@ -183,35 +184,6 @@ impl Waymark {
}
}

#[derive(Bundle)]
struct WaymarkBundle {
name: Name,
waymark: Waymark,
transform: Transform,
visibility: Visibility,
collider: Collider,
colliding: CollidingEntities,
alpha: AlphaScale,
}

impl WaymarkBundle {
fn new(waymark: Waymark) -> Self {
Self {
name: Name::new(waymark.name()),
waymark,
transform: default(),
visibility: default(),
collider: if waymark.is_square() {
Collider::rectangle(WAYMARK_SIZE, WAYMARK_SIZE)
} else {
Collider::circle(WAYMARK_SIZE / 2.0)
},
colliding: default(),
alpha: default(),
}
}
}

struct InsertWaymark {
waymark: Waymark,
entry: Option<PresetEntry>,
Expand All @@ -228,7 +200,6 @@ impl EntityCommand for InsertWaymark {
let mut arena_q = world.query::<&ArenaBackground>();
match arena_q.get_single(world) {
Ok(arena) => {
debug!("positioning waymark {waymark:?} when arena loaded");
world.run_system_when_asset_loaded_with(
arena.handle.id(),
set_position_from_preset,
Expand All @@ -244,8 +215,17 @@ impl EntityCommand for InsertWaymark {
let Ok(mut entity) = world.get_entity_mut(id) else {
return;
};
entity.insert(WaymarkBundle::new(waymark));
entity.insert((
Name::new(waymark.name()),
waymark,
if waymark.is_square() {
Collider::rectangle(WAYMARK_SIZE, WAYMARK_SIZE)
} else {
Collider::circle(WAYMARK_SIZE / 2.0)
},
));
make_draggable_world(&mut entity);

entity.with_children(|parent| {
parent.spawn((
Name::new("Waymark Image"),
Expand Down Expand Up @@ -317,6 +297,12 @@ fn set_position_from_preset(
let Ok(mut entity) = world.get_entity_mut(id) else {
return;
};
let (x, y) = (entry.x - offset.x, offset.y - entry.z);
debug!(
"arena loaded, repositioning waymark {} to {:?}",
entry.id,
(x, y),
);
entity.insert(Transform::from_xyz(
entry.x - offset.x,
// The entry's Z axis is our negative Y axis.
Expand All @@ -325,8 +311,7 @@ fn set_position_from_preset(
));
}

/// [`EntityCommand`] to insert a waymark's entities.
///
//
/// If a [`PresetEntry`] is provided, it will be used to position the waymark.
pub fn insert_waymark(waymark: Waymark, entry: Option<PresetEntry>) -> impl EntityCommand {
InsertWaymark { waymark, entry }
Expand Down
62 changes: 41 additions & 21 deletions src/waymark/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bevy::ecs::system::SystemState;
use bevy::prelude::*;

use bevy::utils::hashbrown::HashMap;
use bevy_egui::egui::TextEdit;
use bevy_egui::egui::{RichText, TextEdit};
use bevy_egui::{egui, EguiClipboard, EguiContexts};

use super::{Preset, Waymark};
Expand Down Expand Up @@ -40,29 +40,16 @@ impl WaymarkWindow {
let (id, mut win) = win_q.single_mut();

ui.horizontal(|ui| {
ui.label("Preset: ");
ui.add(TextEdit::singleline(&mut win.preset_name).desired_width(100.0));
ui.label("Preset Name: ");
ui.add(TextEdit::singleline(&mut win.preset_name).desired_width(80.0));
});
ui.horizontal(|ui| {
if ui.button("Import").clicked() {
if let Some(contents) = clipboard.get_contents() {
match serde_json::from_str::<Preset>(&contents) {
Ok(preset) => {
win.preset_name = preset.name.clone();
commands.run_system_cached(Waymark::despawn_all);
Waymark::spawn_from_preset(&mut commands, preset);
info!(
"Imported waymark preset '{}' from the clipboard",
win.preset_name
);
}
Err(e) => {
info!("Unable to import waymark preset: {}", e);
}
}
} else {
info!("Unable to import waymark preset: clipboard is empty")
}
Self::import_from_clipboard(
&mut win.preset_name,
&mut clipboard,
&mut commands,
);
}
if ui.button("Export").clicked() {
commands.run_system_cached(Self::export_to_clipboard);
Expand All @@ -71,6 +58,8 @@ impl WaymarkWindow {
commands.run_system_cached(Waymark::despawn_all);
}
});
#[cfg(target_arch = "wasm32")]
ui.label(RichText::new("To paste, press Ctrl-C then click Import.").italics());

let spawners: HashMap<_, _> = spawner_q
.iter_mut()
Expand All @@ -95,6 +84,37 @@ impl WaymarkWindow {
});
}

fn import_from_clipboard(
preset_name: &mut String,
clipboard: &mut EguiClipboard,
commands: &mut Commands,
) {
let Some(contents) = clipboard.get_contents() else {
info!("Unable to import waymarks: clipboard unavailable");
return;
};

if contents.is_empty() {
info!("Unable to import waymarks: clipboard is empty (or unavailable)");
return;
}

match serde_json::from_str::<Preset>(&contents) {
Ok(preset) => {
*preset_name = preset.name.clone();
commands.run_system_cached(Waymark::despawn_all);
Waymark::spawn_from_preset(commands, preset);
info!(
"Imported waymark preset '{}' from the clipboard",
preset_name
);
}
Err(e) => {
info!("Unable to import waymarks: invalid preset: {}", e);
}
}
}

/// [System] that exports the currently-spawned waymarks to the clipboard.
pub fn export_to_clipboard(
win_q: Query<&WaymarkWindow>,
Expand Down

0 comments on commit 034c2ae

Please sign in to comment.