node_engine 0.7.0

Node graph engine for Shader graph or Geometry graph.
Documentation
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
use core::any::Any;
use std::sync::Arc;

use heck::ToTitleCase;
use indexmap::IndexSet;

use glam::{Mat2, Mat3, Mat4, Vec2, Vec3, Vec4};

use anyhow::{Result, anyhow};

#[cfg(feature = "egui")]
use crate::ui::*;
use crate::*;

pub mod types;
pub use types::*;

pub mod vector;
pub use vector::*;

pub mod scalar;

pub mod matrix;
pub use matrix::*;

pub mod texture;

pub mod bindings;
pub use bindings::*;

#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TextureHandleInner {
  pub id: uuid::Uuid,
  pub name: String,
}

#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Texture2DHandle(Option<Arc<TextureHandleInner>>);

#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Texture2DArrayHandle(Option<Arc<TextureHandleInner>>);

#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Texture3DHandle(Option<Arc<TextureHandleInner>>);

#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CubemapHandle(Option<Arc<TextureHandleInner>>);

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Value {
  I32(i32),
  U32(u32),
  F32(f32),
  Vec2(Vec2),
  Vec3(Vec3),
  Vec4(Vec4),
  Mat2(Mat2),
  Mat3(Mat3),
  Mat4(Mat4),
  Texture2D(Texture2DHandle),
  Texture2DArray(Texture2DArrayHandle),
  Texture3D(Texture3DHandle),
  Cubemap(CubemapHandle),
}

impl Default for Value {
  fn default() -> Self {
    Self::F32(Default::default())
  }
}

impl Value {
  pub fn as_any(&self) -> &dyn Any {
    match self {
      Self::I32(v) => v,
      Self::U32(v) => v,
      Self::F32(v) => v,
      Self::Vec2(v) => v,
      Self::Vec3(v) => v,
      Self::Vec4(v) => v,
      Self::Mat2(v) => v,
      Self::Mat3(v) => v,
      Self::Mat4(v) => v,
      Self::Texture2D(v) => v,
      Self::Texture2DArray(v) => v,
      Self::Texture3D(v) => v,
      Self::Cubemap(v) => v,
    }
  }

  pub fn data_type(&self) -> DataType {
    match self {
      Self::I32(_) => DataType::I32,
      Self::U32(_) => DataType::U32,
      Self::F32(_) => DataType::F32,
      Self::Vec2(_) => DataType::Vec2,
      Self::Vec3(_) => DataType::Vec3,
      Self::Vec4(_) => DataType::Vec4,
      Self::Mat2(_) => DataType::Mat2,
      Self::Mat3(_) => DataType::Mat3,
      Self::Mat4(_) => DataType::Mat4,
      Self::Texture2D(_) => DataType::Texture2D,
      Self::Texture2DArray(_) => DataType::Texture2DArray,
      Self::Texture3D(_) => DataType::Texture3D,
      Self::Cubemap(_) => DataType::Cubemap,
    }
  }

  pub fn compile(&self) -> Result<CompiledValue> {
    let value = match self {
      Value::I32(val) => {
        format!("{val:?}")
      }
      Value::U32(val) => {
        format!("{val:?}")
      }
      Value::F32(val) => {
        format!("{val:?}")
      }
      Value::Vec2(v) => {
        format!("vec2<f32>({:?}, {:?})", v.x, v.y)
      }
      Value::Vec3(v) => {
        format!("vec3<f32>({:?}, {:?}, {:?})", v.x, v.y, v.z)
      }
      Value::Vec4(v) => {
        format!("vec4<f32>({:?}, {:?}, {:?}, {:?})", v.x, v.y, v.z, v.w)
      }
      Value::Mat2(m) => {
        let col0 = m.col(0).compile()?;
        let col1 = m.col(1).compile()?;
        format!("mat2x2({col0}, {col1})")
      }
      Value::Mat3(m) => {
        let col0 = m.col(0).compile()?;
        let col1 = m.col(1).compile()?;
        let col2 = m.col(2).compile()?;
        format!("mat3x3({col0}, {col1}, {col2})")
      }
      Value::Mat4(m) => {
        let col0 = m.col(0).compile()?;
        let col1 = m.col(1).compile()?;
        let col2 = m.col(2).compile()?;
        let col3 = m.col(3).compile()?;
        format!("mat4x4({col0}, {col1}, {col2}, {col3})")
      }
      Value::Texture2D(_) => {
        // TODO: Convert to wgsl syntax.
        format!("vec4<f32>(0.5, 0.5, 0., 1.)")
      }
      Value::Texture2DArray(_) => {
        // TODO: Convert to wgsl syntax.
        format!("vec4<f32>(0.5, 0.5, 0., 1.)")
      }
      Value::Texture3D(_) => {
        // TODO: Convert to wgsl syntax.
        format!("vec4<f32>(0.5, 0.5, 0., 1.)")
      }
      Value::Cubemap(_) => {
        // TODO: Convert to wgsl syntax.
        format!("vec4<f32>(0.5, 0.5, 0., 1.)")
      }
    };
    Ok(CompiledValue {
      value,
      dt: self.data_type(),
    })
  }

  #[cfg(feature = "egui")]
  pub fn ui(&mut self, ui: &mut egui::Ui) -> bool {
    match self {
      Self::I32(v) => v.ui(ui),
      Self::U32(v) => v.ui(ui),
      Self::F32(v) => v.ui(ui),
      Self::Vec2(v) => v.ui(ui),
      Self::Vec3(v) => v.ui(ui),
      Self::Vec4(v) => v.ui(ui),
      Self::Mat2(v) => v.ui(ui),
      Self::Mat3(v) => v.ui(ui),
      Self::Mat4(v) => v.ui(ui),
      Self::Texture2D(v) => v.ui(ui),
      Self::Texture2DArray(v) => v.ui(ui),
      Self::Texture3D(v) => v.ui(ui),
      Self::Cubemap(v) => v.ui(ui),
    }
  }
}

impl From<i32> for Value {
  fn from(v: i32) -> Self {
    Self::I32(v)
  }
}

impl From<u32> for Value {
  fn from(v: u32) -> Self {
    Self::U32(v)
  }
}

impl From<f32> for Value {
  fn from(v: f32) -> Self {
    Self::F32(v)
  }
}

impl From<Vec2> for Value {
  fn from(v: Vec2) -> Self {
    Self::Vec2(v)
  }
}

impl From<Vec3> for Value {
  fn from(v: Vec3) -> Self {
    Self::Vec3(v)
  }
}

impl From<Vec4> for Value {
  fn from(v: Vec4) -> Self {
    Self::Vec4(v)
  }
}

impl From<Mat2> for Value {
  fn from(v: Mat2) -> Self {
    Self::Mat2(v)
  }
}

impl From<Mat3> for Value {
  fn from(v: Mat3) -> Self {
    Self::Mat3(v)
  }
}

impl From<Mat4> for Value {
  fn from(v: Mat4) -> Self {
    Self::Mat4(v)
  }
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct InputDefinition {
  pub name: String,
  pub field_name: String,
  pub value_type: DataType,
  pub color: Option<ecolor::Color32>,
}

impl InputDefinition {
  pub fn typed<T: ValueType + Default>(field_name: &str) -> (String, Self) {
    let val = T::default();
    Self::new(field_name, val.data_type())
  }

  pub fn new(field_name: &str, value_type: DataType) -> (String, Self) {
    let name = field_name.to_title_case();
    (
      name.clone(),
      Self {
        name,
        field_name: field_name.to_string(),
        value_type,
        color: None,
      },
    )
  }

  pub fn set_color(&mut self, color: Option<u32>) {
    self.color = color.map(u32_to_color);
  }

  pub fn default_value(&self) -> Value {
    self.value_type.default_value()
  }

  pub fn validate(&self, input: &Input) -> Result<()> {
    match input {
      Input::Disconnect => (),
      Input::Value(val) => {
        let in_type = val.data_type();
        if self.value_type != in_type {
          return Err(anyhow::anyhow!(
            "Wrong input data type: expected {:?} got {:?}",
            self.value_type,
            in_type
          ));
        }
      }
      Input::Connect(_, _) => (),
    }
    Ok(())
  }
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OutputDefinition {
  pub name: String,
  pub field_name: String,
  pub value_type: DataType,
  pub color: Option<ecolor::Color32>,
}

impl OutputDefinition {
  pub fn typed<T: ValueType + Default>(field_name: &str) -> (String, Self) {
    let val = T::default();
    Self::new(field_name, val.data_type())
  }

  pub fn new(field_name: &str, value_type: DataType) -> (String, Self) {
    let name = field_name.to_title_case();
    (
      name.clone(),
      Self {
        name,
        field_name: field_name.to_string(),
        value_type,
        color: None,
      },
    )
  }

  pub fn set_color(&mut self, color: Option<u32>) {
    self.color = color.map(u32_to_color);
  }

  pub fn default_value(&self) -> Value {
    self.value_type.default_value()
  }
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParameterDataType {
  Value(DataType),
  Text(String),
  Select(IndexSet<String>),
}

impl ParameterDataType {
  pub fn select(values: &[&str]) -> Self {
    Self::Select(values.iter().map(|s| s.to_string()).collect())
  }

  pub fn default_value(&self) -> ParameterValue {
    match self {
      Self::Value(dt) => ParameterValue::Value(dt.default_value()),
      Self::Text(val) => ParameterValue::Text(val.clone()),
      Self::Select(values) => {
        let val = values.first().cloned().unwrap_or_default();
        ParameterValue::Selected(val)
      }
    }
  }
}

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
  Value(Value),
  Text(String),
  Selected(String),
}

impl ParameterValue {
  pub fn parameter_data_type(&self) -> ParameterDataType {
    match self {
      Self::Value(val) => ParameterDataType::Value(val.data_type()),
      Self::Text(val) => ParameterDataType::Text(val.clone()),
      Self::Selected(val) => ParameterDataType::Select([val].into_iter().cloned().collect()),
    }
  }
}

impl<T: Into<Value>> From<T> for ParameterValue {
  fn from(v: T) -> Self {
    Self::Value(v.into())
  }
}

impl From<&'static str> for ParameterValue {
  fn from(v: &'static str) -> Self {
    Self::Selected(v.to_string())
  }
}

pub trait ParameterType {
  fn get_param(&self) -> ParameterValue;

  fn set_param(&mut self, value: ParameterValue) -> Result<()>;

  fn parameter_data_type() -> ParameterDataType;

  #[cfg(feature = "egui")]
  fn parameter_ui(
    &mut self,
    def: &ParameterDefinition,
    ui: &mut egui::Ui,
    _id: NodeId,
    _details: bool,
  ) -> bool {
    ui.horizontal(|ui| {
      let mut value = self.get_param();
      ui.label(&def.name);
      if def.ui(ui, &mut value) {
        if let Err(err) = self.set_param(value) {
          log::error!("Failed to update node parameter: {err:?}");
        }
        true
      } else {
        false
      }
    })
    .inner
  }
}

impl<T> ParameterType for T
where
  T: ValueType + Default,
{
  fn get_param(&self) -> ParameterValue {
    ParameterValue::Value(self.to_value())
  }

  fn set_param(&mut self, value: ParameterValue) -> Result<()> {
    match value {
      ParameterValue::Value(val) => {
        self.set_value(val)?;
        Ok(())
      }
      _ => Err(anyhow!("Unsupport ParameterValue -> Value conversion.")),
    }
  }

  fn parameter_data_type() -> ParameterDataType {
    let val = T::default();
    ParameterDataType::Value(val.data_type())
  }

  #[cfg(feature = "egui")]
  fn parameter_ui(
    &mut self,
    def: &ParameterDefinition,
    ui: &mut egui::Ui,
    _id: NodeId,
    _details: bool,
  ) -> bool {
    ui.horizontal(|ui| {
      ui.label(&def.name);
      self.ui(ui)
    })
    .inner
  }
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ParameterDefinition {
  pub name: String,
  pub field_name: String,
  pub param_type: ParameterDataType,
}

impl ParameterDefinition {
  pub fn typed<T: ParameterType>(field_name: &str) -> (String, Self) {
    Self::new(field_name, T::parameter_data_type())
  }

  pub fn new(field_name: &str, param_type: ParameterDataType) -> (String, Self) {
    let name = field_name.to_title_case();
    (
      name.clone(),
      Self {
        name,
        field_name: field_name.to_string(),
        param_type,
      },
    )
  }

  pub fn value(name: &str, data_type: DataType) -> (String, Self) {
    Self::new(name, ParameterDataType::Value(data_type))
  }

  pub fn select(name: &str, values: &[&str]) -> (String, Self) {
    Self::new(name, ParameterDataType::select(values))
  }

  pub fn default_value(&self) -> ParameterValue {
    self.param_type.default_value()
  }

  pub fn validate(&self, value: &ParameterValue) -> Result<()> {
    match (&self.param_type, value) {
      (ParameterDataType::Value(data_type), ParameterValue::Value(val)) => {
        let in_type = val.data_type();
        if data_type != &in_type {
          Err(anyhow::anyhow!(
            "Wrong parameter type: expected {:?} got {:?}",
            data_type,
            in_type
          ))
        } else {
          Ok(())
        }
      }
      (ParameterDataType::Select(values), ParameterValue::Selected(val)) => {
        if values.contains(val) {
          Ok(())
        } else {
          Err(anyhow::anyhow!(
            "Invalid parameter selected value: {:?}",
            val
          ))
        }
      }
      (expected, got) => Err(anyhow::anyhow!(
        "Wrong parameter type: expected {:?} got {:?}",
        expected,
        got
      )),
    }
  }

  #[cfg(feature = "egui")]
  pub fn ui(&self, ui: &mut egui::Ui, value: &mut ParameterValue) -> bool {
    ui.horizontal(|ui| match (&self.param_type, value) {
      (ParameterDataType::Value(_), ParameterValue::Value(value)) => value.ui(ui),
      (ParameterDataType::Select(values), ParameterValue::Selected(selected)) => {
        let mut changed = false;
        egui::ComboBox::from_id_salt(&self.field_name)
          .selected_text(selected.as_str())
          .show_ui(ui, |ui| {
            for value in values {
              if ui
                .selectable_value(selected, value.to_string(), value)
                .changed()
              {
                changed = true;
              }
            }
          });
        changed
      }
      _ => {
        ui.label("Invalid node parameter.  The value and definition don't match.");
        false
      }
    })
    .inner
  }
}

#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct OutputTyped<T, const N: u32, const C: u32 = 0> {
  _phantom: core::marker::PhantomData<T>,
  /// Used for Dynamic outputs.
  concrete_type: Option<DataType>,
}

impl<T: ValueType + Default, const N: u32, const C: u32> OutputTyped<T, N, C> {
  pub fn data_type(&self) -> DataType {
    self
      .concrete_type
      .unwrap_or_else(|| T::default().data_type())
  }

  pub fn is_dynamic(&self) -> bool {
    T::default().data_type().is_dynamic()
  }

  pub fn update_concrete_type(&mut self, concrete_type: &NodeConcreteType) -> bool {
    let dt = T::default().data_type();
    let new_type = match dt {
      DataType::Dynamic => concrete_type.data_type(),
      DataType::DynamicVector => match concrete_type.min {
        Some(DynamicSize::D2) => Some(DataType::Vec2),
        Some(DynamicSize::D3) => Some(DataType::Vec3),
        Some(DynamicSize::D4) => Some(DataType::Vec4),
        _ => Some(DataType::F32),
      },
      DataType::DynamicMatrix => match concrete_type.min {
        Some(DynamicSize::D2) => Some(DataType::Mat2),
        Some(DynamicSize::D3) => Some(DataType::Mat3),
        Some(DynamicSize::D4) => Some(DataType::Mat4),
        _ => None,
      },
      _ => None,
    };
    if new_type != self.concrete_type {
      self.concrete_type = new_type;
      true
    } else {
      false
    }
  }

  pub fn compile(
    &self,
    compile: &mut NodeGraphCompile,
    node: NodeId,
    prefix: &str,
    code: String,
    dt: DataType,
  ) -> Result<()> {
    compile.add_output(OutputId::new(node, N), prefix, code, dt)
  }
}

#[cfg(feature = "egui")]
impl<T: ValueType + Default, const N: u32, const C: u32> OutputTyped<T, N, C> {
  #[cfg(feature = "egui")]
  pub fn ui(
    &mut self,
    concrete_type: &mut NodeConcreteType,
    def: &OutputDefinition,
    ui: &mut egui::Ui,
    id: NodeId,
    details: bool,
  ) {
    ui.horizontal(|ui| {
      ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
        if self.is_dynamic() && self.update_concrete_type(concrete_type) {
          if let Some(graph) = NodeGraphMeta::get(ui) {
            graph.update_output(OutputId::new(id, N));
          }
        }
        if !details {
          ui.add(NodeSocket::output(id, N, def, self.concrete_type));
        }
        ui.label(&def.name);
      });
    });
  }
}

#[cfg(test)]
mod test {
  use super::*;

  #[derive(Clone, Debug, Default)]
  pub struct TestOutput {
    pub _out0: OutputTyped<f32, { 0 + 0 }, 0>,
    pub _out1: OutputTyped<f32, { 0 + 1 }, 0>,
  }

  #[test]
  fn test_typed_outputs() {
    let test = TestOutput::default();
    eprintln!("{test:?}");
  }
}