aboutsummaryrefslogtreecommitdiffstats
path: root/src/node.rs
blob: 859799b445ccb2108b21b94f1b8f89ba2badae52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use enum_dispatch::enum_dispatch;
use std::fmt;

use crate::library;
use crate::library::*;
use crate::types::{Type, TypeSignature};

/// an instantiable Node, parametrized by its connected input types
#[enum_dispatch]
pub trait ConcreteNode {
    fn max_inputs(&self) -> usize;

    // set of possible input type combinations given current connections
    fn signatures_matching(&self, connected: &[Option<Type>]) -> Vec<TypeSignature>;

    fn signature(&self, connected: &[Option<Type>]) -> TypeSignature;

    fn compile(
        &self,
        signature: TypeSignature,
        inputs: Vec<String>,
        outputs: Vec<String>,
        f: &mut dyn fmt::Write,
    ) -> fmt::Result;

    fn show_body(&mut self, ui: &mut egui::Ui) -> egui::Response {
        ui.response()
    }
}

#[enum_dispatch(ConcreteNode)]
#[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum AnyNode {
    Constant(library::AnyConstant),
    Conversion(library::Conversion),
    Input(library::Input),
    Builtin(library::BuiltinFunction),
    Output(library::Output),
}

impl NodeIndex for AnyNode {
    const TITLE: &'static str = "";

    fn all() -> impl Iterator<Item = Self> {
        (library::AnyConstant::all().map(AnyNode::from))
            .chain(library::Conversion::all().map(AnyNode::from))
            .chain(library::Input::all().map(AnyNode::from))
            .chain(library::Output::all().map(AnyNode::from))
            .chain(library::BuiltinFunction::all().map(AnyNode::from))
    }

    fn pick_node(ui: &mut egui::Ui) -> Option<Self> {
        ui.label("Add node");

        let a = library::AnyConstant::pick_node(ui).map(AnyNode::from);
        let b = library::Conversion::pick_node(ui).map(AnyNode::from);
        let c = library::Input::pick_node(ui).map(AnyNode::from);
        let d = library::Output::pick_node(ui).map(AnyNode::from);
        let e = library::BuiltinFunction::pick_node(ui).map(AnyNode::from);

        a.or(b).or(c).or(d).or(e)
    }
}

impl fmt::Display for AnyNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Constant(x) => fmt::Display::fmt(x, f),
            Self::Conversion(x) => fmt::Display::fmt(x, f),
            Self::Input(x) => fmt::Display::fmt(x, f),
            Self::Builtin(x) => fmt::Display::fmt(x, f),
            Self::Output(x) => fmt::Display::fmt(x, f),
        }
    }
}