Finish up initial implementation. Add example code

This commit is contained in:
Setzer22 2022-02-19 12:28:58 +01:00
parent 180c5bd962
commit a40d2343f3
32 changed files with 2812 additions and 41 deletions

View File

@ -1,20 +1,5 @@
[package]
name = "egui_node_graph"
description = "A helper library to create interactive node graphs using egui"
homepage = "https://github.com/setzer22/egui_node_graph"
repository = "https://github.com/setzer22/egui_node_graph"
license = "MIT"
version = "0.1.0"
keywords = ["ui", "egui", "graph", "node"]
authors = ["setzer22"]
edition = "2021"
[features]
persistence = ["serde", "slotmap/serde", "smallvec/serde"]
[dependencies]
egui = { version = "0.16" }
slotmap = { version = "1.0" }
smallvec = { version = "1.7.0" }
serde = { version = "1.0", optional = true, features = ["derive"] }
thiserror = "1.0"
[workspace]
members = [
"egui_node_graph",
"egui_node_graph_example",
]

View File

@ -0,0 +1,22 @@
[package]
name = "egui_node_graph"
description = "A helper library to create interactive node graphs using egui"
homepage = "https://github.com/setzer22/egui_node_graph"
repository = "https://github.com/setzer22/egui_node_graph"
license = "MIT"
version = "0.1.0"
keywords = ["ui", "egui", "graph", "node"]
authors = ["setzer22"]
edition = "2021"
readme = "../README.md"
workspace = ".."
[features]
persistence = ["serde", "slotmap/serde", "smallvec/serde"]
[dependencies]
egui = { version = "0.16" }
slotmap = { version = "1.0" }
smallvec = { version = "1.7.0" }
serde = { version = "1.0", optional = true, features = ["derive"] }
thiserror = "1.0"

View File

@ -0,0 +1,94 @@
use egui::Color32;
/// Converts a hex string with a leading '#' into a egui::Color32.
/// - The first three channels are interpreted as R, G, B.
/// - The fourth channel, if present, is used as the alpha value.
/// - Both upper and lowercase characters can be used for the hex values.
///
/// *Adapted from: https://docs.rs/raster/0.1.0/src/raster/lib.rs.html#425-725.
/// Credit goes to original authors.*
pub fn color_from_hex(hex: &str) -> Result<Color32, String> {
// Convert a hex string to decimal. Eg. "00" -> 0. "FF" -> 255.
fn _hex_dec(hex_string: &str) -> Result<u8, String> {
match u8::from_str_radix(hex_string, 16) {
Ok(o) => Ok(o),
Err(e) => Err(format!("Error parsing hex: {}", e)),
}
}
if hex.len() == 9 && hex.starts_with('#') {
// #FFFFFFFF (Red Green Blue Alpha)
return Ok(Color32::from_rgba_premultiplied(
_hex_dec(&hex[1..3])?,
_hex_dec(&hex[3..5])?,
_hex_dec(&hex[5..7])?,
_hex_dec(&hex[7..9])?,
));
} else if hex.len() == 7 && hex.starts_with('#') {
// #FFFFFF (Red Green Blue)
return Ok(Color32::from_rgb(
_hex_dec(&hex[1..3])?,
_hex_dec(&hex[3..5])?,
_hex_dec(&hex[5..7])?,
));
}
Err(format!(
"Error parsing hex: {}. Example of valid formats: #FFFFFF or #ffffffff",
hex
))
}
/// Converts a Color32 into its canonical hexadecimal representation.
/// - The color string will be preceded by '#'.
/// - If the alpha channel is completely opaque, it will be ommitted.
/// - Characters from 'a' to 'f' will be written in lowercase.
#[allow(dead_code)]
pub fn color_to_hex(color: Color32) -> String {
if color.a() < 255 {
format!(
"#{:02x?}{:02x?}{:02x?}{:02x?}",
color.r(),
color.g(),
color.b(),
color.a()
)
} else {
format!("#{:02x?}{:02x?}{:02x?}", color.r(), color.g(), color.b())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn test_color_from_and_to_hex() {
assert_eq!(
color_from_hex("#00ff00").unwrap(),
Color32::from_rgb(0, 255, 0)
);
assert_eq!(
color_from_hex("#5577AA").unwrap(),
Color32::from_rgb(85, 119, 170)
);
assert_eq!(
color_from_hex("#E2e2e277").unwrap(),
Color32::from_rgba_premultiplied(226, 226, 226, 119)
);
assert!(color_from_hex("abcdefgh").is_err());
assert_eq!(
color_to_hex(Color32::from_rgb(0, 255, 0)),
"#00ff00".to_string()
);
assert_eq!(
color_to_hex(Color32::from_rgb(85, 119, 170)),
"#5577aa".to_string()
);
assert_eq!(
color_to_hex(Color32::from_rgba_premultiplied(226, 226, 226, 119)),
"e2e2e277".to_string()
);
}
}

View File

@ -0,0 +1,600 @@
use std::collections::HashSet;
use crate::color_hex_utils::*;
use crate::utils::ColorUtils;
use super::*;
use egui::epaint::RectShape;
use egui::*;
pub type PortLocations = std::collections::HashMap<AnyParameterId, Pos2>;
pub enum DrawGraphNodeResponse {
ConnectEventStarted(NodeId, AnyParameterId),
ConnectEventEnded(AnyParameterId),
SetActiveNode(NodeId),
SelectNode(NodeId),
RunNodeSideEffect(NodeId),
ClearActiveNode,
DeleteNode(NodeId),
DisconnectEvent(InputId),
/// Emitted when a node is interacted with, and should be raised
RaiseNode(NodeId),
}
pub struct GraphNodeWidget<'a, NodeData, DataType, ValueType> {
pub position: &'a mut Pos2,
pub graph: &'a mut Graph<NodeData, DataType, ValueType>,
pub port_locations: &'a mut PortLocations,
pub node_id: NodeId,
pub ongoing_drag: Option<(NodeId, AnyParameterId)>,
pub active: bool,
pub selected: bool,
pub pan: egui::Vec2,
}
pub trait InputParamWidget {
fn value_widget(&mut self, param_name: &str, ui: &mut Ui);
}
pub trait DataTypeTrait: PartialEq + Eq {
// The associated port color of this datatype
fn data_type_color(&self) -> egui::Color32;
// The name of this datatype
fn name(&self) -> &str;
}
impl<NodeData, DataType, ValueType, NodeKind>
GraphEditorState<NodeData, DataType, ValueType, NodeKind>
where
ValueType: InputParamWidget,
NodeKind: NodeKindTrait<NodeData = NodeData, DataType = DataType, ValueType = ValueType>,
DataType: DataTypeTrait,
{
pub fn draw_graph_editor(
&mut self,
ctx: &CtxRef,
all_kinds: impl NodeKindIter<Item = NodeKind>,
) {
let mouse = &ctx.input().pointer;
let cursor_pos = mouse.hover_pos().unwrap_or(Pos2::ZERO);
// Gets filled with the port locations as nodes are drawn
let mut port_locations = PortLocations::new();
// The responses returned from node drawing have side effects that are best
// executed at the end of this function.
let mut delayed_responses: Vec<DrawGraphNodeResponse> = vec![];
// Used to detect when the background was clicked, to dismiss certain selfs
let mut click_on_background = false;
debug_assert_eq!(
self.node_order.iter().copied().collect::<HashSet<_>>(),
self.graph.iter_nodes().collect::<HashSet<_>>(),
"The node_order field of the GraphEditorself was left in an \
inconsistent self. It has either more or less values than the graph."
);
CentralPanel::default().show(ctx, |ui| {
/* Draw nodes */
for node_id in self.node_order.iter().copied() {
let responses = GraphNodeWidget {
position: self.node_positions.get_mut(node_id).unwrap(),
graph: &mut self.graph,
port_locations: &mut port_locations,
node_id,
ongoing_drag: self.connection_in_progress,
active: self
.active_node
.map(|active| active == node_id)
.unwrap_or(false),
selected: self
.selected_node
.map(|selected| selected == node_id)
.unwrap_or(false),
pan: self.pan_zoom.pan,
}
.show(ui);
// Actions executed later
delayed_responses.extend(responses);
}
let r = ui.allocate_rect(ui.min_rect(), Sense::click());
if r.clicked() {
click_on_background = true;
}
});
/* Draw the node finder, if open */
let mut should_close_node_finder = false;
if let Some(ref mut node_finder) = self.node_finder {
let mut node_finder_area = Area::new("node_finder");
if let Some(pos) = node_finder.position {
node_finder_area = node_finder_area.current_pos(pos);
}
node_finder_area.show(ctx, |ui| {
if let Some(node_kind) = node_finder.show(ui, all_kinds) {
let new_node = self.graph.add_node(
node_kind.node_graph_label(),
node_kind.user_data(),
|graph, node_id| node_kind.build_node(graph, node_id),
);
self.node_positions
.insert(new_node, cursor_pos - self.pan_zoom.pan);
self.node_order.push(new_node);
should_close_node_finder = true;
}
});
}
if should_close_node_finder {
self.node_finder = None;
}
/* Draw connections */
let connection_stroke = egui::Stroke {
width: 5.0,
color: color_from_hex("#efefef").unwrap(),
};
if let Some((_, ref locator)) = self.connection_in_progress {
let painter = ctx.layer_painter(LayerId::background());
let start_pos = port_locations[locator];
painter.line_segment([start_pos, cursor_pos], connection_stroke)
}
for (input, output) in self.graph.iter_connections() {
let painter = ctx.layer_painter(LayerId::background());
let src_pos = port_locations[&AnyParameterId::Output(output)];
let dst_pos = port_locations[&AnyParameterId::Input(input)];
painter.line_segment([src_pos, dst_pos], connection_stroke);
}
/* Handle responses from drawing nodes */
for response in delayed_responses {
match response {
DrawGraphNodeResponse::ConnectEventStarted(node_id, port) => {
self.connection_in_progress = Some((node_id, port));
}
DrawGraphNodeResponse::ConnectEventEnded(locator) => {
let in_out = match (
self.connection_in_progress
.map(|(_node, param)| param)
.take()
.expect("Cannot end drag without in-progress connection."),
locator,
) {
(AnyParameterId::Input(input), AnyParameterId::Output(output))
| (AnyParameterId::Output(output), AnyParameterId::Input(input)) => {
Some((input, output))
}
_ => None,
};
if let Some((input, output)) = in_out {
self.graph.add_connection(output, input)
}
}
DrawGraphNodeResponse::SetActiveNode(node_id) => {
self.active_node = Some(node_id);
}
DrawGraphNodeResponse::SelectNode(node_id) => {
self.selected_node = Some(node_id);
}
DrawGraphNodeResponse::ClearActiveNode => {
self.active_node = None;
}
DrawGraphNodeResponse::RunNodeSideEffect(node_id) => {
self.run_side_effect = Some(node_id);
}
DrawGraphNodeResponse::DeleteNode(node_id) => {
self.graph.remove_node(node_id);
self.node_positions.remove(node_id);
// Make sure to not leave references to old nodes hanging
if self.active_node.map(|x| x == node_id).unwrap_or(false) {
self.active_node = None;
}
if self.selected_node.map(|x| x == node_id).unwrap_or(false) {
self.selected_node = None;
}
if self.run_side_effect.map(|x| x == node_id).unwrap_or(false) {
self.run_side_effect = None;
}
self.node_order.retain(|id| *id != node_id);
}
DrawGraphNodeResponse::DisconnectEvent(input_id) => {
let corresp_output = self
.graph
.connection(input_id)
.expect("Connection data should be valid");
let other_node = self.graph.get_input(input_id).node();
self.graph.remove_connection(input_id);
self.connection_in_progress =
Some((other_node, AnyParameterId::Output(corresp_output)));
}
DrawGraphNodeResponse::RaiseNode(node_id) => {
let old_pos = self
.node_order
.iter()
.position(|id| *id == node_id)
.expect("Node to be raised should be in `node_order`");
self.node_order.remove(old_pos);
self.node_order.push(node_id);
}
}
}
/* Mouse input handling */
if mouse.any_released() && self.connection_in_progress.is_some() {
self.connection_in_progress = None;
}
if mouse.button_down(PointerButton::Secondary) {
self.node_finder = Some(NodeFinder::new_at(cursor_pos));
}
if ctx.input().key_pressed(Key::Escape) {
self.node_finder = None;
}
if ctx.input().pointer.middle_down() {
self.pan_zoom.pan += ctx.input().pointer.delta();
}
if click_on_background {
self.selected_node = None;
self.node_finder = None;
}
}
}
impl<'a, NodeData, DataType, ValueType> GraphNodeWidget<'a, NodeData, DataType, ValueType>
where
ValueType: InputParamWidget,
DataType: DataTypeTrait,
{
pub const MAX_NODE_SIZE: [f32; 2] = [200.0, 200.0];
pub fn show(self, ui: &mut Ui) -> Vec<DrawGraphNodeResponse> {
let mut child_ui = ui.child_ui_with_id_source(
Rect::from_min_size(*self.position + self.pan, Self::MAX_NODE_SIZE.into()),
Layout::default(),
self.node_id,
);
Self::show_graph_node(self, &mut child_ui)
}
/// Draws this node. Also fills in the list of port locations with all of its ports.
/// Returns a response showing whether a drag event was started.
/// Parameters:
/// - **ongoing_drag**: Is there a port drag event currently going on?
fn show_graph_node(self, ui: &mut Ui) -> Vec<DrawGraphNodeResponse> {
let margin = egui::vec2(15.0, 5.0);
let _field_separation = 5.0;
let mut responses = Vec::<DrawGraphNodeResponse>::new();
let background_color = color_from_hex("#3f3f3f").unwrap();
let titlebar_color = background_color.lighten(0.8);
let text_color = color_from_hex("#fefefe").unwrap();
ui.visuals_mut().widgets.noninteractive.fg_stroke = Stroke::new(2.0, text_color);
// Preallocate shapes to paint below contents
let outline_shape = ui.painter().add(Shape::Noop);
let background_shape = ui.painter().add(Shape::Noop);
let outer_rect_bounds = ui.available_rect_before_wrap();
let mut inner_rect = outer_rect_bounds.shrink2(margin);
// Make sure we don't shrink to the negative:
inner_rect.max.x = inner_rect.max.x.max(inner_rect.min.x);
inner_rect.max.y = inner_rect.max.y.max(inner_rect.min.y);
let mut child_ui = ui.child_ui(inner_rect, *ui.layout());
let mut title_height = 0.0;
let mut input_port_heights = vec![];
let mut output_port_heights = vec![];
child_ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.add(Label::new(
RichText::new(&self.graph[self.node_id].label)
.text_style(TextStyle::Button)
.color(color_from_hex("#fefefe").unwrap()),
));
});
ui.add_space(margin.y);
title_height = ui.min_size().y;
// First pass: Draw the inner fields. Compute port heights
let inputs = self.graph[self.node_id].inputs.clone();
for (param_name, param_id) in inputs {
if self.graph[param_id].shown_inline {
let height_before = ui.min_rect().bottom();
if self.graph.connection(param_id).is_some() {
ui.label(param_name);
} else {
self.graph[param_id].value.value_widget(&param_name, ui);
}
let height_after = ui.min_rect().bottom();
input_port_heights.push((height_before + height_after) / 2.0);
}
}
let outputs = self.graph[self.node_id].outputs.clone();
for (param_name, _param) in outputs {
let height_before = ui.min_rect().bottom();
ui.label(&param_name);
let height_after = ui.min_rect().bottom();
output_port_heights.push((height_before + height_after) / 2.0);
}
/* TODO: Restore button row
// Button row
ui.horizontal(|ui| {
// Show 'Enable' button for nodes that output a mesh
if self.graph[self.node_id].can_be_enabled(self.graph) {
ui.horizontal(|ui| {
if !self.active {
if ui.button("👁 Set active").clicked() {
responses.push(DrawGraphNodeResponse::SetActiveNode(self.node_id));
}
} else {
let button = egui::Button::new(
RichText::new("👁 Active").color(egui::Color32::BLACK),
)
.fill(egui::Color32::GOLD);
if ui.add(button).clicked() {
responses.push(DrawGraphNodeResponse::ClearActiveNode);
}
}
});
}
// Show 'Run' button for executable nodes
if self.graph[self.node_id].is_executable() && ui.button("⛭ Run").clicked() {
responses.push(DrawGraphNodeResponse::RunNodeSideEffect(self.node_id));
}
})
*/
});
// Second pass, iterate again to draw the ports. This happens outside
// the child_ui because we want ports to overflow the node background.
let outer_rect = child_ui.min_rect().expand2(margin);
let port_left = outer_rect.left();
let port_right = outer_rect.right();
#[allow(clippy::too_many_arguments)]
fn draw_port<NodeData, DataType, ValueType>(
ui: &mut Ui,
graph: &Graph<NodeData, DataType, ValueType>,
node_id: NodeId,
port_pos: Pos2,
responses: &mut Vec<DrawGraphNodeResponse>,
param_id: AnyParameterId,
port_locations: &mut PortLocations,
ongoing_drag: Option<(NodeId, AnyParameterId)>,
is_connected_input: bool,
) where
DataType: DataTypeTrait,
{
let port_type = graph.any_param_type(param_id).unwrap();
let port_rect = Rect::from_center_size(port_pos, egui::vec2(10.0, 10.0));
let sense = if ongoing_drag.is_some() {
Sense::hover()
} else {
Sense::click_and_drag()
};
let resp = ui.allocate_rect(port_rect, sense);
let port_color = if resp.hovered() {
Color32::WHITE
} else {
port_type.data_type_color()
};
ui.painter()
.circle(port_rect.center(), 5.0, port_color, Stroke::none());
if resp.drag_started() {
if is_connected_input {
responses.push(DrawGraphNodeResponse::DisconnectEvent(
param_id.assume_input(),
));
} else {
responses.push(DrawGraphNodeResponse::ConnectEventStarted(
node_id, param_id,
));
}
}
if let Some((origin_node, origin_param)) = ongoing_drag {
if origin_node != node_id {
// Don't allow self-loops
if graph.any_param_type(origin_param).unwrap() == port_type
&& resp.hovered()
&& ui.input().pointer.any_released()
{
responses.push(DrawGraphNodeResponse::ConnectEventEnded(param_id));
}
}
}
port_locations.insert(param_id, port_rect.center());
}
// Input ports
for ((_, param), port_height) in self.graph[self.node_id]
.inputs
.iter()
.zip(input_port_heights.into_iter())
{
let should_draw = match self.graph[*param].kind() {
InputParamKind::ConnectionOnly => true,
InputParamKind::ConstantOnly => false,
InputParamKind::ConnectionOrConstant => true,
};
if should_draw {
let pos_left = pos2(port_left, port_height);
draw_port(
ui,
self.graph,
self.node_id,
pos_left,
&mut responses,
AnyParameterId::Input(*param),
self.port_locations,
self.ongoing_drag,
self.graph.connection(*param).is_some(),
);
}
}
// Output ports
for ((_, param), port_height) in self.graph[self.node_id]
.outputs
.iter()
.zip(output_port_heights.into_iter())
{
let pos_right = pos2(port_right, port_height);
draw_port(
ui,
self.graph,
self.node_id,
pos_right,
&mut responses,
AnyParameterId::Output(*param),
self.port_locations,
self.ongoing_drag,
false,
);
}
// Draw the background shape.
// NOTE: This code is a bit more involve than it needs to be because egui
// does not support drawing rectangles with asymmetrical round corners.
let (shape, outline) = {
let corner_radius = 4.0;
let titlebar_height = title_height + margin.y;
let titlebar_rect =
Rect::from_min_size(outer_rect.min, vec2(outer_rect.width(), titlebar_height));
let titlebar = Shape::Rect(RectShape {
rect: titlebar_rect,
corner_radius,
fill: titlebar_color,
stroke: Stroke::none(),
});
let body_rect = Rect::from_min_size(
outer_rect.min + vec2(0.0, titlebar_height - corner_radius),
vec2(outer_rect.width(), outer_rect.height() - titlebar_height),
);
let body = Shape::Rect(RectShape {
rect: body_rect,
corner_radius: 0.0,
fill: background_color,
stroke: Stroke::none(),
});
let bottom_body_rect = Rect::from_min_size(
body_rect.min + vec2(0.0, body_rect.height() - titlebar_height * 0.5),
vec2(outer_rect.width(), titlebar_height),
);
let bottom_body = Shape::Rect(RectShape {
rect: bottom_body_rect,
corner_radius,
fill: background_color,
stroke: Stroke::none(),
});
let outline = if self.selected {
Shape::Rect(RectShape {
rect: titlebar_rect
.union(body_rect)
.union(bottom_body_rect)
.expand(1.0),
corner_radius: 4.0,
fill: Color32::WHITE.lighten(0.8),
stroke: Stroke::none(),
})
} else {
Shape::Noop
};
(Shape::Vec(vec![titlebar, body, bottom_body]), outline)
};
ui.painter().set(background_shape, shape);
ui.painter().set(outline_shape, outline);
// --- Interaction ---
// Titlebar buttons
if Self::close_button(ui, outer_rect).clicked() {
responses.push(DrawGraphNodeResponse::DeleteNode(self.node_id));
};
let window_response = ui.interact(
outer_rect,
Id::new((self.node_id, "window")),
Sense::click_and_drag(),
);
// Movement
*self.position += window_response.drag_delta();
if window_response.drag_delta().length_sq() > 0.0 {
responses.push(DrawGraphNodeResponse::RaiseNode(self.node_id));
}
// Node selection
//
// HACK: Only set the select response when no other response is active.
// This prevents some issues.
if responses.is_empty() && window_response.clicked_by(PointerButton::Primary) {
responses.push(DrawGraphNodeResponse::SelectNode(self.node_id));
responses.push(DrawGraphNodeResponse::RaiseNode(self.node_id));
}
responses
}
fn close_button(ui: &mut Ui, node_rect: Rect) -> Response {
// Measurements
let margin = 8.0;
let size = 10.0;
let stroke_width = 2.0;
let offs = margin + size / 2.0;
let position = pos2(node_rect.right() - offs, node_rect.top() + offs);
let rect = Rect::from_center_size(position, vec2(size, size));
let resp = ui.allocate_rect(rect, Sense::click());
let color = if resp.clicked() {
color_from_hex("#ffffff").unwrap()
} else if resp.hovered() {
color_from_hex("#dddddd").unwrap()
} else {
color_from_hex("#aaaaaa").unwrap()
};
let stroke = Stroke {
width: stroke_width,
color,
};
ui.painter()
.line_segment([rect.left_top(), rect.right_bottom()], stroke);
ui.painter()
.line_segment([rect.right_top(), rect.left_bottom()], stroke);
resp
}
}

View File

@ -1,3 +1,5 @@
use egui::plot::Value;
use super::*;
impl<NodeData, DataType, ValueType> Graph<NodeData, DataType, ValueType> {
@ -14,7 +16,7 @@ impl<NodeData, DataType, ValueType> Graph<NodeData, DataType, ValueType> {
&mut self,
label: String,
user_data: NodeData,
f: impl FnOnce(NodeId, &mut Node<NodeData>),
f: impl FnOnce(&mut Graph<NodeData, DataType, ValueType>, NodeId),
) -> NodeId {
let node_id = self.nodes.insert_with_key(|node_id| {
Node {
@ -27,11 +29,42 @@ impl<NodeData, DataType, ValueType> Graph<NodeData, DataType, ValueType> {
}
});
f(node_id, self.nodes.get_mut(node_id).unwrap());
f(self, node_id);
node_id
}
pub fn add_input_param(
&mut self,
node_id: NodeId,
name: String,
typ: DataType,
value: ValueType,
kind: InputParamKind,
shown_inline: bool,
) -> InputId {
let input_id = self.inputs.insert_with_key(|input_id| InputParam {
id: input_id,
typ,
value,
kind,
node: node_id,
shown_inline,
});
self.nodes[node_id].inputs.push((name, input_id));
input_id
}
pub fn add_output_param(&mut self, node_id: NodeId, name: String, typ: DataType) -> OutputId {
let output_id = self.outputs.insert_with_key(|output_id| OutputParam {
id: output_id,
node: node_id,
typ,
});
self.nodes[node_id].outputs.push((name, output_id));
output_id
}
pub fn remove_node(&mut self, node_id: NodeId) {
self.connections
.retain(|i, o| !(self.outputs[*o].node == node_id || self.inputs[i].node == node_id));
@ -127,4 +160,18 @@ impl<NodeData> Node<NodeData> {
.map(|x| x.1)
.ok_or_else(|| EguiGraphError::NoParameterNamed(self.id, name.into()))
}
}
}
impl<DataType, ValueType> InputParam<DataType, ValueType> {
pub fn value(&self) -> &ValueType {
&self.value
}
pub fn kind(&self) -> InputParamKind {
self.kind
}
pub fn node(&self) -> NodeId {
self.node
}
}

View File

@ -16,6 +16,13 @@ pub use ui_state::*;
pub mod node_finder;
pub use node_finder::*;
pub mod editor_ui;
pub use editor_ui::*;
mod utils;
mod color_hex_utils;
#[cfg(feature = "persistence")]
use serde::{Deserialize, Serialize};

View File

@ -1,9 +1,9 @@
use std::marker::PhantomData;
use super::*;
use crate::{color_hex_utils::*, Graph, Node, NodeId};
use egui::*;
#[derive(Default)]
pub struct NodeFinder<NodeKind> {
query: String,
/// Reset every frame. When set, the node finder will be moved at that position
@ -14,25 +14,55 @@ pub struct NodeFinder<NodeKind> {
pub trait NodeKindIter {
type Item;
fn all_kinds<'a>() -> Box<dyn Iterator<Item=&'a Self::Item>>;
fn all_kinds(&self) -> Box<dyn Iterator<Item = &Self::Item> + '_>;
}
impl<NodeKind> NodeFinder<NodeKind> {
pub trait NodeKindTrait: Clone {
type NodeData;
type DataType;
type ValueType;
/// Returns a descriptive name for the node kind, used in the node finder.
fn node_finder_label(&self) -> &str;
/// Returns a descriptive name for the node kind, used in the graph.
fn node_graph_label(&self) -> String;
/// Returns the user data for this node kind.
fn user_data(&self) -> Self::NodeData;
/// This function is run when this node kind gets added to the graph. The
/// node will be empty by default, and this function can be used to fill its
/// parameters.
fn build_node(
&self,
graph: &mut Graph<Self::NodeData, Self::DataType, Self::ValueType>,
node_id: NodeId,
);
}
impl<NodeKind, NodeData> NodeFinder<NodeKind>
where
NodeKind: NodeKindTrait<NodeData = NodeData>,
{
pub fn new_at(pos: Pos2) -> Self {
NodeFinder {
query: "".into(),
position: Some(pos),
just_spawned: true,
_phantom: Default::default(),
..Default::default()
}
}
/// Shows the node selector panel with a search bar. Returns whether a node
/// archetype was selected and, in that case, the finder should be hidden on
/// the next frame.
pub fn show(&mut self, ui: &mut Ui, all_kinds: impl NodeKindIter<Item=NodeKind>) -> Option<NodeKind> {
pub fn show(
&mut self,
ui: &mut Ui,
all_kinds: impl NodeKindIter<Item = NodeKind>,
) -> Option<NodeKind> {
let background_color = color_from_hex("#3f3f3f").unwrap();
let _titlebar_color = background_color.linear_multiply(0.8);
let text_color = color_from_hex("#fefefe").unwrap();
ui.visuals_mut().widgets.noninteractive.fg_stroke = Stroke::new(2.0, text_color);
@ -54,15 +84,15 @@ impl<NodeKind> NodeFinder<NodeKind> {
let mut query_submit = resp.lost_focus() && ui.input().key_down(Key::Enter);
Frame::default().margin(vec2(10.0, 10.0)).show(ui, |ui| {
for archetype in all_kinds.all_kinds() {
let archetype_name = archetype.type_label();
if archetype_name.contains(self.query.as_str()) {
for kind in all_kinds.all_kinds() {
let kind_name = kind.node_finder_label();
if kind_name.contains(self.query.as_str()) {
if query_submit {
submitted_archetype = Some(archetype);
submitted_archetype = Some(kind);
query_submit = false;
}
if ui.selectable_label(false, archetype_name).clicked() {
submitted_archetype = Some(archetype);
if ui.selectable_label(false, kind_name).clicked() {
submitted_archetype = Some(kind);
}
}
}
@ -70,6 +100,6 @@ impl<NodeKind> NodeFinder<NodeKind> {
});
});
submitted_archetype
submitted_archetype.cloned()
}
}

View File

@ -1,7 +1,7 @@
use super::*;
#[cfg(feature = "persistence")]
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
#[derive(Copy, Clone)]
#[cfg_attr(feature = "persistence", derive(Serialize, Deserialize))]
@ -10,7 +10,7 @@ pub struct PanZoom {
pub zoom: f32,
}
pub struct GraphEditorState<NodeData, DataType, ValueType> {
pub struct GraphEditorState<NodeData, DataType, ValueType, NodeKind> {
pub graph: Graph<NodeData, DataType, ValueType>,
/// Nodes are drawn in this order. Draw order is important because nodes
/// that are drawn last are on top.
@ -27,7 +27,7 @@ pub struct GraphEditorState<NodeData, DataType, ValueType> {
/// The position of each node.
pub node_positions: SecondaryMap<NodeId, egui::Pos2>,
/// The node finder is used to create new nodes.
pub node_finder: Option<NodeFinder>,
pub node_finder: Option<NodeFinder<NodeKind>>,
/// When this option is set by the UI, the side effect encoded by the node
/// will be executed at the start of the next frame.
pub run_side_effect: Option<NodeId>,
@ -35,7 +35,9 @@ pub struct GraphEditorState<NodeData, DataType, ValueType> {
pub pan_zoom: PanZoom,
}
impl<NodeData, DataType, ValueType> GraphEditorState<NodeData, DataType, ValueType> {
impl<NodeData, DataType, ValueType, NodeKind>
GraphEditorState<NodeData, DataType, ValueType, NodeKind>
{
pub fn new(default_zoom: f32) -> Self {
Self {
graph: Graph::new(),

View File

@ -0,0 +1,15 @@
pub trait ColorUtils {
/// Multiplies the color rgb values by `factor`, keeping alpha untouched.
fn lighten(&self, factor: f32) -> Self;
}
impl ColorUtils for egui::Color32 {
fn lighten(&self, factor: f32) -> Self {
egui::Color32::from_rgba_premultiplied(
(self.r() as f32 * factor) as u8,
(self.g() as f32 * factor) as u8,
(self.b() as f32 * factor) as u8,
self.a(),
)
}
}

1
egui_node_graph_example/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

View File

@ -0,0 +1,19 @@
[package]
name = "egui_node_graph_example"
version = "0.1.0"
authors = ["setzer22"]
edition = "2021"
rust-version = "1.56"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
eframe = "0.16.0"
egui_node_graph = { path = "../egui_node_graph" }
[features]
default = []
[profile.release]
opt-level = 2 # fast and small wasm

View File

@ -0,0 +1,78 @@
@echo off
SET script_path=%~dp0
cd %script_path%
SET OPEN=0
SET FAST=0
:do_while
IF (%1) == () GOTO end_while
IF %1 == -h GOTO print_help
IF %1 == --help GOTO print_help
IF %1 == --fast (
SET FAST=1
SHIFT
GOTO do_while
)
IF %1 == --open (
SET OPEN=1
SHIFT
GOTO do_while
)
echo Unknown command "%1"
:end_while
@REM call this first : `./setup_web.bat`
for %%I in (.) do SET FOLDER_NAME=%%~nxI
@REM assume crate name is the same as the folder name
SET CRATE_NAME=%FOLDER_NAME%
@REM for those who name crates with-kebab-case
SET CRATE_NAME_SNAKE_CASE=%FOLDER_NAME:-=_%
@REM This is required to enable the web_sys clipboard API which egui_web uses
@REM https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Clipboard.html
@REM https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
SET RUSTFLAGS=--cfg=web_sys_unstable_apis
@REM Clear output from old stuff:
DEL /F docs\%CRATE_NAME_SNAKE_CASE%_bg.wasm
echo Building rust...
SET BUILD=release
cargo build -p %CRATE_NAME% --release --lib --target wasm32-unknown-unknown
@REM Get the output directory (in the workspace it is in another location)
FOR /F %%i IN ('cargo metadata --format-version=1 ^| jq --raw-output .target_directory') DO SET TARGET=%%i
echo Generating JS bindings for wasm...
SET TARGET_NAME=%CRATE_NAME_SNAKE_CASE%.wasm
wasm-bindgen "%TARGET%\wasm32-unknown-unknown\%BUILD%\%TARGET_NAME%" --out-dir "docs" --no-modules --no-typescript
IF %FAST% == 0 (
echo Optimizing wasm...
@REM to get wasm-opt: apt/brew/dnf install binaryen
@REM add -g to get debug symbols :
wasm-opt "docs\%CRATE_NAME%_bg.wasm" -O2 --fast-math -o "docs\%CRATE_NAME%_bg.wasm"
)
echo Finished: docs/%CRATE_NAME_SNAKE_CASE%.wasm"
IF %OPEN% == 1 start http://localhost:8080/index.html
GOTO end_program
:print_help
echo build_web.sh [--fast] [--open]
echo --fast: skip optimization step
echo --open: open the result in a browser
GOTO end_program
:end_program

View File

@ -0,0 +1,76 @@
#!/bin/bash
set -eu
script_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )
cd "$script_path"
OPEN=false
FAST=false
while test $# -gt 0; do
case "$1" in
-h|--help)
echo "build_web.sh [--fast] [--open]"
echo " --fast: skip optimization step"
echo " --open: open the result in a browser"
exit 0
;;
--fast)
shift
FAST=true
;;
--open)
shift
OPEN=true
;;
*)
break
;;
esac
done
# ./setup_web.sh # <- call this first!
FOLDER_NAME=${PWD##*/}
CRATE_NAME=$FOLDER_NAME # assume crate name is the same as the folder name
CRATE_NAME_SNAKE_CASE="${CRATE_NAME//-/_}" # for those who name crates with-kebab-case
# This is required to enable the web_sys clipboard API which egui_web uses
# https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Clipboard.html
# https://rustwasm.github.io/docs/wasm-bindgen/web-sys/unstable-apis.html
export RUSTFLAGS=--cfg=web_sys_unstable_apis
# Clear output from old stuff:
rm -f "docs/${CRATE_NAME_SNAKE_CASE}_bg.wasm"
echo "Building rust…"
BUILD=release
cargo build -p "${CRATE_NAME}" --release --lib --target wasm32-unknown-unknown
# Get the output directory (in the workspace it is in another location)
TARGET=$(cargo metadata --format-version=1 | jq --raw-output .target_directory)
echo "Generating JS bindings for wasm…"
TARGET_NAME="${CRATE_NAME_SNAKE_CASE}.wasm"
wasm-bindgen "${TARGET}/wasm32-unknown-unknown/${BUILD}/${TARGET_NAME}" \
--out-dir docs --no-modules --no-typescript
if [[ "${FAST}" == false ]]; then
echo "Optimizing wasm…"
# to get wasm-opt: apt/brew/dnf install binaryen
wasm-opt "docs/${CRATE_NAME}_bg.wasm" -O2 --fast-math -o "docs/${CRATE_NAME}_bg.wasm" # add -g to get debug symbols
fi
echo "Finished: docs/${CRATE_NAME_SNAKE_CASE}.wasm"
if [[ "${OPEN}" == true ]]; then
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux, ex: Fedora
xdg-open http://localhost:8080/index.html
elif [[ "$OSTYPE" == "msys" ]]; then
# Windows
start http://localhost:8080/index.html
else
# Darwin/MacOS, or something else
open http://localhost:8080/index.html
fi
fi

View File

@ -0,0 +1,10 @@
#!/bin/bash
# This scripts runs various CI-like checks in a convenient way.
set -eux
cargo check --workspace --all-targets
cargo check --workspace --all-features --lib --target wasm32-unknown-unknown
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings -W clippy::all
cargo test --workspace --all-targets --all-features
cargo test --workspace --doc

View File

@ -0,0 +1,3 @@
This folder contains the files required for the web app.
The reason the folder is called "docs" is because that is the name that GitHub requires in order to host a web page from the `master` branch of a repository. You can test the `eframe_template` at <https://emilk.github.io/eframe_template/>.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

View File

@ -0,0 +1,152 @@
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- Disable zooming: -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<head>
<title>eframe template</title>
<style>
html {
/* Remove touch delay: */
touch-action: manipulation;
}
body {
/* Light mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #909090;
}
@media (prefers-color-scheme: dark) {
body {
/* Dark mode background color for what is not covered by the egui canvas,
or where the egui canvas is translucent. */
background: #404040;
}
}
/* Allow canvas to fill entire web page: */
html,
body {
overflow: hidden;
margin: 0 !important;
padding: 0 !important;
}
/* Position canvas in center-top: */
canvas {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 0%;
left: 50%;
transform: translate(-50%, 0%);
}
.loading {
margin-right: auto;
margin-left: auto;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 24px;
font-family: Ubuntu-Light, Helvetica, sans-serif;
}
/* ---------------------------------------------- */
/* Loading animation from https://loading.io/css/ */
.lds-dual-ring {
display: inline-block;
width: 24px;
height: 24px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 24px;
height: 24px;
margin: 0px;
border-radius: 50%;
border: 3px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
<link rel="manifest" href="./manifest.json">
<script>
// register ServiceWorker
window.onload = () => {
'use strict';
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./sw.js');
}
}
</script>
</head>
<body>
<!-- The WASM code will resize this canvas to cover the entire screen -->
<canvas id="the_canvas_id"></canvas>
<div class="loading" id="loading">
Loading…&nbsp;&nbsp;
<div class="lds-dual-ring"></div>
</div>
<script>
// The `--no-modules`-generated JS from `wasm-bindgen` attempts to use
// `WebAssembly.instantiateStreaming` to instantiate the wasm module,
// but this doesn't work with `file://` urls. This example is frequently
// viewed by simply opening `index.html` in a browser (with a `file://`
// url), so it would fail if we were to call this function!
//
// Work around this for now by deleting the function to ensure that the
// `no_modules.js` script doesn't have access to it. You won't need this
// hack when deploying over HTTP.
delete WebAssembly.instantiateStreaming;
</script>
<!-- This is the JS generated by the `wasm-bindgen` CLI tool -->
<script src="eframe_template.js"></script>
<script>
// We'll defer our execution until the wasm is ready to go.
// Here we tell bindgen the path to the wasm file so it can start
// initialization and return to us a promise when it's done.
wasm_bindgen("./eframe_template_bg.wasm")
.then(on_wasm_loaded)
.catch(console.error);
function on_wasm_loaded() {
console.log("loaded wasm, starting egui app…");
// This call installs a bunch of callbacks and then returns:
wasm_bindgen.start("the_canvas_id");
console.log("egui app started.");
document.getElementById("loading").remove();
}
</script>
</body>
</html>
<!-- Powered by egui: https://github.com/emilk/egui/ -->

View File

@ -0,0 +1,14 @@
{
"name": "Egui Template PWA",
"short_name": "egui-template-pwa",
"icons": [{
"src": "./icon-256.png",
"sizes": "256x256",
"type": "image/png"
}],
"lang": "en-US",
"start_url": "./index.html",
"display": "standalone",
"background_color": "white",
"theme_color": "white"
}

View File

@ -0,0 +1,25 @@
var cacheName = 'egui-template-pwa';
var filesToCache = [
'./',
'./index.html',
'./eframe_template.js',
'./eframe_template_bg.wasm',
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function (e) {
e.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll(filesToCache);
})
);
});
/* Serve cached content when offline */
self.addEventListener('fetch', function (e) {
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request);
})
);
});

View File

@ -0,0 +1,7 @@
@REM Pre-requisites:
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
cargo update -p wasm-bindgen
@REM For local tests with `./start_server`:
cargo install basic-http-server

View File

@ -0,0 +1,10 @@
#!/bin/bash
set -eu
# Pre-requisites:
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli
cargo update -p wasm-bindgen
# For local tests with `./start_server`:
cargo install basic-http-server

View File

@ -0,0 +1,245 @@
use eframe::{
egui::{self, DragValue},
epi,
};
use egui_node_graph::*;
// ========= First, define your user data types =============
/// The NodeData holds a custom data struct inside each node. It's useful to
/// store additional information that doesn't live in parameters. For this
/// simple example we don't really want to store anything.
pub struct MyNodeData;
/// `DataType`s are what defines the possible range of connections when
/// attaching two ports together. The graph UI will make sure to not allow
/// attaching incompatible datatypes.
#[derive(PartialEq, Eq)]
pub enum MyDataType {
Scalar,
Vec2,
}
/// In the graph, input parameters can optionally have a constant value. This
/// value can be directly edited in a widget inside the node itself.
///
/// There will usually be a correspondence between DataTypes and ValueTypes. But
/// this library makes no attempt to check this consistency. For instance, it is
/// up to the user code in this example to make sure no parameter is created
/// with a DataType of Scalar and a ValueType of Vec2.
pub enum MyValueType {
Vec2 { value: egui::Vec2 },
Scalar { value: f32 },
}
/// NodeKind is a mechanism to define node "templates". It's what the graph will
/// display in the "new node" popup. The user code needs to tell the library how
/// to convert a NodeKind into a Node.
#[derive(Clone, Copy)]
pub enum MyNodeKind {
AddScalar,
SubtractScalar,
VectorTimesScalar,
AddVector,
}
// =========== Then, you need to implement some traits ============
// A trait for the data types, to tell the library how to display them
impl DataTypeTrait for MyDataType {
fn data_type_color(&self) -> egui::Color32 {
match self {
MyDataType::Scalar => egui::Color32::from_rgb(38, 109, 211),
MyDataType::Vec2 => egui::Color32::from_rgb(238, 207, 109),
}
}
fn name(&self) -> &str {
match self {
MyDataType::Scalar => "scalar",
MyDataType::Vec2 => "2d vector",
}
}
}
// A trait for the node kinds, which tells the library how to build new nodes
// from the templates in the node finder
impl NodeKindTrait for MyNodeKind {
type NodeData = MyNodeData;
type DataType = MyDataType;
type ValueType = MyValueType;
fn node_finder_label(&self) -> &str {
match self {
MyNodeKind::AddScalar => "Scalar add",
MyNodeKind::SubtractScalar => "Scalar subtract",
MyNodeKind::VectorTimesScalar => "Vector times scalar",
MyNodeKind::AddVector => "Vector subtract",
}
}
fn node_graph_label(&self) -> String {
// It's okay to delegate this to node_finder_label if you don't want to
// show different names in the node finder and the node itself.
self.node_finder_label().into()
}
fn user_data(&self) -> Self::NodeData {
MyNodeData
}
fn build_node(
&self,
graph: &mut Graph<Self::NodeData, Self::DataType, Self::ValueType>,
node_id: NodeId,
) {
// The nodes are created empty by default. This function needs to take
// care of creating the desired inputs and outputs based on the template
// We define some macros here to avoid boilerplate. Note that this is
// entirely optional.
macro_rules! input {
(scalar $name:expr) => {
graph.add_input_param(
node_id,
$name.to_string(),
MyDataType::Scalar,
MyValueType::Scalar { value: 0.0 },
InputParamKind::ConnectionOrConstant,
true,
);
};
(vector $name:expr) => {
graph.add_input_param(
node_id,
$name.to_string(),
MyDataType::Vec2,
MyValueType::Vec2 {
value: egui::vec2(0.0, 0.0),
},
InputParamKind::ConnectionOrConstant,
true,
);
};
}
macro_rules! output {
(scalar $name:expr) => {
graph.add_output_param(node_id, $name.to_string(), MyDataType::Scalar);
};
(vector $name:expr) => {
graph.add_output_param(node_id, $name.to_string(), MyDataType::Vec2);
};
}
match self {
MyNodeKind::AddScalar => {
// The first input param doesn't use the macro so we can comment
// it in more detail.
graph.add_input_param(
node_id,
// This is the name of the parameter. Can be later used to
// retrieve the value. Parameter names should be unique.
"A".into(),
// The data type for this input. In this case, a scalar
MyDataType::Scalar,
// The value type for this input. We store zero as default
MyValueType::Scalar { value: 0.0 },
// The input parameter kind. This allows defining whether a
// parameter accepts input connections and/or an inline
// widget to set its value.
InputParamKind::ConnectionOrConstant,
true,
);
input!(scalar "B");
output!(scalar "out");
}
MyNodeKind::SubtractScalar => {
input!(scalar "A");
input!(scalar "B");
output!(scalar "out");
}
MyNodeKind::VectorTimesScalar => {
input!(scalar "scalar");
input!(vector "vector");
output!(vector "out");
}
MyNodeKind::AddVector => {
input!(vector "v1");
input!(vector "v2");
output!(vector "out");
}
}
}
}
pub struct AllMyNodeKinds;
impl NodeKindIter for AllMyNodeKinds {
type Item = MyNodeKind;
fn all_kinds(&self) -> Box<dyn Iterator<Item = &Self::Item> + '_> {
// This function must return a list of node kinds, which the node finder
// will use to display it to the user. Crates like strum can reduce the
// boilerplate in enumerating all variants of an enum.
//
// The Box here is required because traits in Rust cannot be generic
// over return parameters, so you can't return an iterator.
Box::new(
[
MyNodeKind::AddScalar,
MyNodeKind::SubtractScalar,
MyNodeKind::VectorTimesScalar,
MyNodeKind::AddVector,
]
.iter(),
)
}
}
impl InputParamWidget for MyValueType {
fn value_widget(&mut self, param_name: &str, ui: &mut egui::Ui) {
// This trait is used to tell the library which UI to display for the
// inline parameter widgets.
match self {
MyValueType::Vec2 { value } => {
ui.label(param_name);
ui.horizontal(|ui| {
ui.label("x");
ui.add(DragValue::new(&mut value.x));
ui.label("y");
ui.add(DragValue::new(&mut value.y));
});
}
MyValueType::Scalar { value } => {
ui.horizontal(|ui| {
ui.label(param_name);
ui.add(DragValue::new(value));
});
}
}
}
}
pub struct NodeGraphExample {
state: GraphEditorState<MyNodeData, MyDataType, MyValueType, MyNodeKind>,
}
impl Default for NodeGraphExample {
fn default() -> Self {
Self {
state: GraphEditorState::new(1.0),
}
}
}
impl epi::App for NodeGraphExample {
fn name(&self) -> &str {
"eframe template"
}
/// Called each time the UI needs repainting, which may be many times per second.
/// Put your widgets into a `SidePanel`, `TopPanel`, `CentralPanel`, `Window` or `Area`.
fn update(&mut self, ctx: &egui::CtxRef, frame: &epi::Frame) {
self.state.draw_graph_editor(ctx, AllMyNodeKinds);
}
}

View File

@ -0,0 +1,23 @@
#![forbid(unsafe_code)]
#![cfg_attr(not(debug_assertions), deny(warnings))] // Forbid warnings in release builds
#![warn(clippy::all, rust_2018_idioms)]
mod app;
pub use app::NodeGraphExample;
// ----------------------------------------------------------------------------
// When compiling for web:
#[cfg(target_arch = "wasm32")]
use eframe::wasm_bindgen::{self, prelude::*};
/// This is the entry-point for all the web-assembly.
/// This is called once from the HTML.
/// It loads the app, installs some callbacks, then returns.
/// You can add more callbacks like this if you want to call in to your code.
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn start(canvas_id: &str) -> Result<(), eframe::wasm_bindgen::JsValue> {
let app = NodeGraphExample::default();
eframe::start_web(canvas_id, Box::new(app))
}

View File

@ -0,0 +1,11 @@
#![forbid(unsafe_code)]
#![cfg_attr(not(debug_assertions), deny(warnings))] // Forbid warnings in release builds
#![warn(clippy::all, rust_2018_idioms)]
// When compiling natively:
#[cfg(not(target_arch = "wasm32"))]
fn main() {
let app = egui_node_graph_example::NodeGraphExample::default();
let native_options = eframe::NativeOptions::default();
eframe::run_native(Box::new(app), native_options);
}

View File

@ -0,0 +1,11 @@
@echo off
@REM Starts a local web-server that serves the contents of the `doc/` folder,
@REM which is the folder to where the web version is compiled.
cargo install basic-http-server
echo "open http://localhost:8080"
(cd docs && basic-http-server --addr 127.0.0.1:8080 .)
@REM (cd docs && python3 -m http.server 8080 --bind 127.0.0.1)

View File

@ -0,0 +1,12 @@
#!/bin/bash
set -eu
# Starts a local web-server that serves the contents of the `doc/` folder,
# which is the folder to where the web version is compiled.
cargo install basic-http-server
echo "open http://localhost:8080"
(cd docs && basic-http-server --addr 127.0.0.1:8080 .)
# (cd docs && python3 -m http.server 8080 --bind 127.0.0.1)