-
-
Notifications
You must be signed in to change notification settings - Fork 226
/
voxel_graph_function.cpp
1505 lines (1297 loc) · 51.4 KB
/
voxel_graph_function.cpp
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "voxel_graph_function.h"
#include "../../constants/voxel_string_names.h"
#include "../../util/container_funcs.h"
#include "../../util/godot/classes/object.h"
#include "../../util/godot/core/array.h" // for `varray` in GDExtension builds
#include "../../util/godot/core/callable.h"
#include "../../util/godot/funcs.h"
#include "../../util/string_funcs.h"
#include "node_type_db.h"
#include <algorithm>
namespace zylann::voxel::pg {
const char *VoxelGraphFunction::SIGNAL_NODE_NAME_CHANGED = "node_name_changed";
void VoxelGraphFunction::clear() {
unregister_subresources();
_graph.clear();
#ifdef TOOLS_ENABLED
_can_load_default_graph = false;
#endif
}
ProgramGraph::Node *create_node_internal(ProgramGraph &graph, VoxelGraphFunction::NodeTypeID type_id, Vector2 position,
uint32_t id, bool create_default_instances) {
const NodeType &type = NodeTypeDB::get_singleton().get_type(type_id);
ProgramGraph::Node *node = graph.create_node(type_id, id);
ERR_FAIL_COND_V(node == nullptr, nullptr);
node->inputs.resize(type.inputs.size());
node->outputs.resize(type.outputs.size());
node->default_inputs.resize(type.inputs.size());
node->gui_position = position;
node->params.resize(type.params.size());
for (size_t i = 0; i < type.params.size(); ++i) {
const NodeType::Param ¶m = type.params[i];
if (param.class_name.is_empty()) {
node->params[i] = param.default_value;
} else if (param.default_value_func != nullptr && create_default_instances) {
node->params[i] = param.default_value_func();
}
}
node->autoconnect_default_inputs = type.has_autoconnect_inputs();
for (size_t i = 0; i < type.inputs.size(); ++i) {
const NodeType::Port &port_spec = type.inputs[i];
node->default_inputs[i] = port_spec.default_value;
node->inputs[i].autoconnect_hint = port_spec.auto_connect;
}
return node;
}
// Automatically chooses inputs and outputs based on a graph.
void auto_pick_input_and_outputs(const ProgramGraph &graph, std::vector<VoxelGraphFunction::Port> &inputs,
std::vector<VoxelGraphFunction::Port> &outputs) {
const NodeTypeDB &type_db = NodeTypeDB::get_singleton();
struct L {
static void try_add_port(
const VoxelGraphFunction::Port &port, std::vector<VoxelGraphFunction::Port> &added_ports) {
for (VoxelGraphFunction::Port &p : added_ports) {
if (p.equals(port)) {
// Already added
return;
}
}
added_ports.push_back(port);
}
static void try_add_port(const ProgramGraph::Node &node, const NodeType &type,
std::vector<VoxelGraphFunction::Port> &added_ports) {
try_add_port(make_port_from_io_node(node, type), added_ports);
}
};
struct Comparator {
// If special input, move to top. Otherwise, use alphanumeric sorting.
bool operator()(const VoxelGraphFunction::Port &a, const VoxelGraphFunction::Port &b) const {
if (a.is_custom()) {
if (b.is_custom()) {
return a.name < b.name;
} else {
return false;
}
} else if (b.is_custom()) {
return true;
} else {
if (a.type == b.type) {
return a.sub_index < b.sub_index;
} else {
return a.type < b.type;
}
}
}
};
inputs.clear();
outputs.clear();
graph.for_each_node_const([&type_db, &inputs, &outputs](const ProgramGraph::Node &node) {
const NodeType &type = type_db.get_type(node.type_id);
if (type.category == CATEGORY_INPUT) {
L::try_add_port(node, type, inputs);
} else if (type.category == CATEGORY_OUTPUT) {
L::try_add_port(node, type, outputs);
} else if (node.autoconnect_default_inputs) {
// The input node is implicit
for (const ProgramGraph::Port &input : node.inputs) {
VoxelGraphFunction::NodeTypeID input_type_id;
// If the input isn't connected and has an autoconnect hint
if (input.connections.size() == 0 &&
VoxelGraphFunction::try_get_node_type_id_from_auto_connect(
VoxelGraphFunction::AutoConnect(input.autoconnect_hint), input_type_id)) {
const NodeType &input_type = type_db.get_type(input_type_id);
ZN_ASSERT(input_type.outputs.size() == 1);
const VoxelGraphFunction::Port port(input_type_id, input_type.outputs[0].name);
L::try_add_port(port, inputs);
}
}
}
});
std::sort(inputs.begin(), inputs.end(), Comparator());
std::sort(outputs.begin(), outputs.end(), Comparator());
}
VoxelGraphFunction::AutoConnect get_auto_connect_hint(const VoxelGraphFunction::Port &port) {
if (!port.is_custom()) {
VoxelGraphFunction::AutoConnect ac;
if (VoxelGraphFunction::try_get_auto_connect_from_node_type_id(port.type, ac)) {
return ac;
}
}
return VoxelGraphFunction::AUTO_CONNECT_NONE;
}
void setup_function(ProgramGraph::Node &node, Ref<VoxelGraphFunction> func) {
ZN_ASSERT(node.type_id == VoxelGraphFunction::NODE_FUNCTION);
ZN_ASSERT(func.is_valid());
ZN_ASSERT(node.params.size() >= 1);
node.params.resize(1);
node.params[0] = func;
Span<const VoxelGraphFunction::Port> input_definitions = func->get_input_definitions();
node.default_inputs.resize(input_definitions.size());
for (Variant &di : node.default_inputs) {
di = 0.f;
}
struct L {
static void set_ports(std::vector<ProgramGraph::Port> &ports, Span<const VoxelGraphFunction::Port> fports) {
ports.clear();
for (const VoxelGraphFunction::Port &fport : fports) {
ProgramGraph::Port port;
port.autoconnect_hint = get_auto_connect_hint(fport);
ports.push_back(port);
}
}
};
L::set_ports(node.inputs, input_definitions);
L::set_ports(node.outputs, func->get_output_definitions());
node.autoconnect_default_inputs = true;
// TODO Function parameters
}
void update_function(
ProgramGraph &graph, uint32_t node_id, std::vector<ProgramGraph::Connection> *removed_connections) {
ProgramGraph::Node &node = graph.get_node(node_id);
ZN_ASSERT(node.type_id == VoxelGraphFunction::NODE_FUNCTION);
ZN_ASSERT_RETURN(node.params.size() >= 1);
Ref<VoxelGraphFunction> func = node.params[0];
ZN_ASSERT_RETURN(func.is_valid());
Span<const VoxelGraphFunction::Port> input_defs = func->get_input_definitions();
Span<const VoxelGraphFunction::Port> output_defs = func->get_output_definitions();
ZN_ASSERT(node.default_inputs.size() == node.inputs.size());
// Update inputs
for (unsigned int input_index = 0; input_index < input_defs.size(); ++input_index) {
const VoxelGraphFunction::Port &port_def = input_defs[input_index];
if (input_index < node.inputs.size()) {
ProgramGraph::Port &port = node.inputs[input_index];
port.autoconnect_hint = get_auto_connect_hint(port_def);
} else {
ProgramGraph::Port port;
port.autoconnect_hint = get_auto_connect_hint(port_def);
node.inputs.push_back(port);
node.default_inputs.push_back(0.f);
}
}
// Remove excess inputs
if (node.inputs.size() > input_defs.size()) {
for (unsigned int i = input_defs.size(); i < node.inputs.size(); ++i) {
const ProgramGraph::Port &port = node.inputs[i];
if (port.connections.size() > 0) {
ZN_ASSERT(port.connections.size() == 1);
const ProgramGraph::PortLocation src = port.connections[0];
const ProgramGraph::PortLocation dst{ node_id, i };
graph.disconnect(src, dst);
if (removed_connections != nullptr) {
removed_connections->push_back(ProgramGraph::Connection{ src, dst });
}
}
}
node.inputs.resize(input_defs.size());
node.default_inputs.resize(input_defs.size());
}
// Add new outputs
for (unsigned int output_index = node.outputs.size(); output_index < output_defs.size(); ++output_index) {
ProgramGraph::Port port;
node.outputs.push_back(port);
}
// Remove excess outputs
if (node.outputs.size() > output_defs.size()) {
for (unsigned int i = output_defs.size(); i < node.outputs.size(); ++i) {
const ProgramGraph::Port &port = node.outputs[i];
const std::vector<ProgramGraph::PortLocation> destinations = port.connections;
const ProgramGraph::PortLocation src{ node_id, i };
for (const ProgramGraph::PortLocation dst : destinations) {
graph.disconnect(src, dst);
if (removed_connections != nullptr) {
removed_connections->push_back(ProgramGraph::Connection{ src, dst });
}
}
}
node.outputs.resize(output_defs.size());
}
}
uint32_t VoxelGraphFunction::create_node(NodeTypeID type_id, Vector2 position, uint32_t id) {
ERR_FAIL_COND_V(!NodeTypeDB::get_singleton().is_valid_type_id(type_id), ProgramGraph::NULL_ID);
ProgramGraph::Node *node = create_node_internal(_graph, type_id, position, id, true);
ERR_FAIL_COND_V(node == nullptr, ProgramGraph::NULL_ID);
// Register resources if any were created by default
for (const Variant &v : node->params) {
if (v.get_type() == Variant::OBJECT) {
Ref<Resource> res = v;
if (res.is_valid()) {
register_subresource(**res);
} else {
ZN_PRINT_WARNING("Non-resource object found in node parameter");
}
}
}
struct L {
static void bind_custom_port(std::vector<VoxelGraphFunction::Port> &ports, ProgramGraph::Node &node) {
for (unsigned int port_index = 0; port_index < ports.size(); ++port_index) {
VoxelGraphFunction::Port &port = ports[port_index];
if (port.is_custom()) {
// ZN_ASSERT(node->params.size() >= 1);
// node->params[0] = input_index;
node.name = port.name;
// port.node_ids.push_back(node.id);
break;
}
}
}
};
if (type_id == NODE_CUSTOM_INPUT) {
L::bind_custom_port(_inputs, *node);
}
if (type_id == NODE_CUSTOM_OUTPUT) {
L::bind_custom_port(_outputs, *node);
}
return node->id;
}
uint32_t VoxelGraphFunction::create_function_node(Ref<VoxelGraphFunction> func, Vector2 position, uint32_t p_id) {
ERR_FAIL_COND_V_MSG(func.is_null(), ProgramGraph::NULL_ID, "Cannot add null function");
ERR_FAIL_COND_V_MSG(func.ptr() == this, ProgramGraph::NULL_ID, "Cannot add function to itself");
ERR_FAIL_COND_V_MSG(func->contains_reference_to_function(*this), ProgramGraph::NULL_ID,
"Cannot add function indirectly referencing itself");
const uint32_t id = create_node(VoxelGraphFunction::NODE_FUNCTION, position, p_id);
ERR_FAIL_COND_V(id == ProgramGraph::NULL_ID, ProgramGraph::NULL_ID);
ProgramGraph::Node &node = _graph.get_node(id);
setup_function(node, func);
register_subresource(**func);
return id;
}
void VoxelGraphFunction::remove_node(uint32_t node_id) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
for (size_t i = 0; i < node->params.size(); ++i) {
Ref<Resource> resource = node->params[i];
if (resource.is_valid()) {
unregister_subresource(**resource);
}
}
_graph.remove_node(node_id);
emit_changed();
}
bool VoxelGraphFunction::can_connect(
uint32_t src_node_id, uint32_t src_port_index, uint32_t dst_node_id, uint32_t dst_port_index) const {
const ProgramGraph::PortLocation src_port{ src_node_id, src_port_index };
const ProgramGraph::PortLocation dst_port{ dst_node_id, dst_port_index };
ERR_FAIL_COND_V(!_graph.is_output_port_valid(src_port), false);
ERR_FAIL_COND_V(!_graph.is_input_port_valid(dst_port), false);
const ProgramGraph::Node &node = _graph.get_node(src_node_id);
// Output nodes have output ports, for internal reasons. They should not be connected.
const NodeType &type = NodeTypeDB::get_singleton().get_type(node.type_id);
if (type.category == CATEGORY_OUTPUT) {
return false;
}
return _graph.can_connect(src_port, dst_port);
}
bool VoxelGraphFunction::is_valid_connection(
uint32_t src_node_id, uint32_t src_port_index, uint32_t dst_node_id, uint32_t dst_port_index) const {
const ProgramGraph::PortLocation src_port{ src_node_id, src_port_index };
const ProgramGraph::PortLocation dst_port{ dst_node_id, dst_port_index };
ERR_FAIL_COND_V(!_graph.is_output_port_valid(src_port), false);
ERR_FAIL_COND_V(!_graph.is_input_port_valid(dst_port), false);
const ProgramGraph::Node &node = _graph.get_node(src_node_id);
const NodeType &type = NodeTypeDB::get_singleton().get_type(node.type_id);
if (type.category == CATEGORY_OUTPUT) {
return false;
}
return _graph.is_valid_connection(src_port, dst_port);
}
void VoxelGraphFunction::add_connection(
uint32_t src_node_id, uint32_t src_port_index, uint32_t dst_node_id, uint32_t dst_port_index) {
const ProgramGraph::PortLocation src_port{ src_node_id, src_port_index };
const ProgramGraph::PortLocation dst_port{ dst_node_id, dst_port_index };
ERR_FAIL_COND(!_graph.is_output_port_valid(src_port));
ERR_FAIL_COND(!_graph.is_input_port_valid(dst_port));
const ProgramGraph::Node &node = _graph.get_node(src_node_id);
const NodeType &type = NodeTypeDB::get_singleton().get_type(node.type_id);
ERR_FAIL_COND(type.category == CATEGORY_OUTPUT);
_graph.connect(src_port, dst_port);
emit_changed();
}
void VoxelGraphFunction::remove_connection(
uint32_t src_node_id, uint32_t src_port_index, uint32_t dst_node_id, uint32_t dst_port_index) {
const ProgramGraph::PortLocation src_port{ src_node_id, src_port_index };
const ProgramGraph::PortLocation dst_port{ dst_node_id, dst_port_index };
ERR_FAIL_COND(!_graph.is_output_port_valid(src_port));
ERR_FAIL_COND(!_graph.is_input_port_valid(dst_port));
_graph.disconnect(src_port, dst_port);
emit_changed();
}
void VoxelGraphFunction::get_connections(std::vector<ProgramGraph::Connection> &p_connections) const {
_graph.get_connections(p_connections);
}
bool VoxelGraphFunction::try_get_connection_to(
ProgramGraph::PortLocation dst, ProgramGraph::PortLocation &out_src) const {
const ProgramGraph::Node &node = _graph.get_node(dst.node_id);
CRASH_COND(dst.port_index >= node.inputs.size());
const ProgramGraph::Port &port = node.inputs[dst.port_index];
if (port.connections.size() == 0) {
return false;
}
// There can be at most one inbound connection
out_src = port.connections[0];
return true;
}
bool VoxelGraphFunction::has_node(uint32_t node_id) const {
return _graph.try_get_node(node_id) != nullptr;
}
void VoxelGraphFunction::set_node_name(uint32_t node_id, StringName p_name) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_MSG(node == nullptr, "No node was found with the specified ID");
if (node->name == p_name) {
return;
}
if (p_name != StringName()) {
const uint32_t existing_node_id = _graph.find_node_by_name(p_name);
if (existing_node_id != ProgramGraph::NULL_ID && node_id == existing_node_id) {
ZN_PRINT_ERROR(format("More than one graph node has the name \"{}\"", String(p_name)));
}
}
node->name = p_name;
emit_signal(SIGNAL_NODE_NAME_CHANGED, node_id);
}
StringName VoxelGraphFunction::get_node_name(uint32_t node_id) const {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, StringName());
return node->name;
}
uint32_t VoxelGraphFunction::find_node_by_name(StringName p_name) const {
return _graph.find_node_by_name(p_name);
}
void VoxelGraphFunction::set_node_param(uint32_t node_id, uint32_t param_index, Variant value) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
ERR_FAIL_INDEX(param_index, node->params.size());
if (node->params[param_index] != value) {
if (node->type_id == VoxelGraphFunction::NODE_FUNCTION && param_index == 0) {
// The function param is special, it conditions the presence of other parameters and node ports
Ref<VoxelGraphFunction> func = value;
ERR_FAIL_COND_MSG(func.is_null(),
String("A Function node with a null {0} reference is not allowed")
.format(varray(VoxelGraphFunction::get_class_static())));
// Unregister potential resource params, since the previous function could have had different ones
for (unsigned int i = 0; i < node->params.size(); ++i) {
Ref<Resource> res = node->params[i];
if (res.is_valid()) {
unregister_subresource(**res);
}
}
setup_function(*node, func);
register_subresource(**func);
} else {
Ref<Resource> prev_resource = node->params[param_index];
if (prev_resource.is_valid()) {
unregister_subresource(**prev_resource);
}
node->params[param_index] = value;
Ref<Resource> resource = value;
if (resource.is_valid()) {
register_subresource(**resource);
}
}
emit_changed();
}
}
bool VoxelGraphFunction::get_expression_variables(std::string_view code, std::vector<std::string_view> &vars) {
Span<const ExpressionParser::Function> functions = NodeTypeDB::get_singleton().get_expression_parser_functions();
ExpressionParser::Result result = ExpressionParser::parse(code, functions);
if (result.error.id == ExpressionParser::ERROR_NONE) {
if (result.root != nullptr) {
ExpressionParser::find_variables(*result.root, vars);
}
return true;
} else {
return false;
}
}
void VoxelGraphFunction::get_expression_node_inputs(uint32_t node_id, std::vector<std::string> &out_names) const {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
ERR_FAIL_COND(node->type_id != NODE_EXPRESSION);
for (unsigned int i = 0; i < node->inputs.size(); ++i) {
const ProgramGraph::Port &port = node->inputs[i];
ERR_FAIL_COND(!port.is_dynamic());
out_names.push_back(port.dynamic_name);
}
}
inline bool has_duplicate(const PackedStringArray &sa) {
return find_duplicate(Span<const String>(sa.ptr(), sa.size())) != size_t(sa.size());
}
void VoxelGraphFunction::set_expression_node_inputs(uint32_t node_id, PackedStringArray input_names) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
// Validate
ERR_FAIL_COND(node == nullptr);
ERR_FAIL_COND(node->type_id != NODE_EXPRESSION);
for (int i = 0; i < input_names.size(); ++i) {
const String input_name = input_names[i];
ERR_FAIL_COND(!input_name.is_valid_identifier());
}
ERR_FAIL_COND(has_duplicate(input_names));
for (unsigned int i = 0; i < node->inputs.size(); ++i) {
const ProgramGraph::Port &port = node->inputs[i];
// Sounds annoying if you call this from a script, but this is supposed to be editor functionality for now
ERR_FAIL_COND_MSG(port.connections.size() > 0,
ZN_TTR("Cannot change input ports if connections exist, disconnect them first."));
}
node->inputs.resize(input_names.size());
node->default_inputs.resize(input_names.size());
for (int i = 0; i < input_names.size(); ++i) {
const String input_name = input_names[i];
const CharString name_utf8 = input_name.utf8();
node->inputs[i].dynamic_name = name_utf8.get_data();
}
}
Variant VoxelGraphFunction::get_node_param(uint32_t node_id, uint32_t param_index) const {
const ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, Variant());
ERR_FAIL_INDEX_V(param_index, node->params.size(), Variant());
return node->params[param_index];
}
Variant VoxelGraphFunction::get_node_default_input(uint32_t node_id, uint32_t input_index) const {
const ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, Variant());
ERR_FAIL_INDEX_V(input_index, node->default_inputs.size(), Variant());
return node->default_inputs[input_index];
}
void VoxelGraphFunction::set_node_default_input(uint32_t node_id, uint32_t input_index, Variant value) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
ERR_FAIL_INDEX(input_index, node->default_inputs.size());
Variant &defval = node->default_inputs[input_index];
if (defval != value) {
// node->autoconnect_default_inputs = false;
defval = value;
emit_changed();
}
}
bool VoxelGraphFunction::get_node_default_inputs_autoconnect(uint32_t node_id) const {
const ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, false);
return node->autoconnect_default_inputs;
}
void VoxelGraphFunction::set_node_default_inputs_autoconnect(uint32_t node_id, bool enabled) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
if (node->autoconnect_default_inputs != enabled) {
node->autoconnect_default_inputs = enabled;
emit_changed();
}
}
Vector2 VoxelGraphFunction::get_node_gui_position(uint32_t node_id) const {
const ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, Vector2());
return node->gui_position;
}
void VoxelGraphFunction::set_node_gui_position(uint32_t node_id, Vector2 pos) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
if (node->gui_position != pos) {
node->gui_position = pos;
}
}
Vector2 VoxelGraphFunction::get_node_gui_size(uint32_t node_id) const {
const ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, Vector2());
return node->gui_size;
}
void VoxelGraphFunction::set_node_gui_size(uint32_t node_id, Vector2 size) {
ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
if (node->gui_size != size) {
node->gui_size = size;
}
}
VoxelGraphFunction::NodeTypeID VoxelGraphFunction::get_node_type_id(uint32_t node_id) const {
const ProgramGraph::Node *node = _graph.try_get_node(node_id);
ERR_FAIL_COND_V(node == nullptr, NODE_TYPE_COUNT);
CRASH_COND(node->type_id >= NODE_TYPE_COUNT);
return (NodeTypeID)node->type_id;
}
PackedInt32Array VoxelGraphFunction::get_node_ids() const {
PackedInt32Array ids;
{
_graph.for_each_node_id([&ids](int id) {
// Not resizing up-front, because the code to assign elements is different between Godot modules and
// GDExtension
ids.append(id);
});
}
return ids;
}
unsigned int VoxelGraphFunction::get_nodes_count() const {
return _graph.get_nodes_count();
}
#ifdef TOOLS_ENABLED
void VoxelGraphFunction::get_configuration_warnings(PackedStringArray &out_warnings) const {}
uint64_t VoxelGraphFunction::get_output_graph_hash() const {
const NodeTypeDB &type_db = NodeTypeDB::get_singleton();
std::vector<uint32_t> terminal_nodes;
// Not using the generic `get_terminal_nodes` function because our terminal nodes do have outputs
_graph.for_each_node_const([&terminal_nodes, &type_db](const ProgramGraph::Node &node) {
const NodeType &type = type_db.get_type(node.type_id);
if (type.category == CATEGORY_OUTPUT) {
terminal_nodes.push_back(node.id);
}
});
// Sort for determinism
std::sort(terminal_nodes.begin(), terminal_nodes.end());
std::vector<uint32_t> order;
_graph.find_dependencies(terminal_nodes, order);
std::vector<uint64_t> node_hashes;
uint64_t hash = hash_djb2_one_64(0);
for (uint32_t node_id : order) {
ProgramGraph::Node &node = _graph.get_node(node_id);
hash = hash_djb2_one_64(node.type_id, hash);
for (const Variant &v : node.params) {
if (v.get_type() == Variant::OBJECT) {
const Object *obj = v.operator Object *();
if (obj != nullptr) {
// Note, the obtained hash can change here even if the result is identical, because it's hard to
// tell which properties contribute to the result. This should be rare though.
hash = hash_djb2_one_64(get_deep_hash(*obj), hash);
}
} else {
hash = hash_djb2_one_64(v.hash(), hash);
}
}
for (const Variant &v : node.default_inputs) {
hash = hash_djb2_one_64(v.hash(), hash);
}
for (const ProgramGraph::Port &port : node.inputs) {
for (const ProgramGraph::PortLocation src : port.connections) {
hash = hash_djb2_one_64(uint64_t(src.node_id) | (uint64_t(src.port_index) << 32), hash);
}
}
}
return hash;
}
#endif
void VoxelGraphFunction::find_dependencies(uint32_t node_id, std::vector<uint32_t> &out_dependencies) const {
std::vector<uint32_t> dst;
dst.push_back(node_id);
_graph.find_dependencies(dst, out_dependencies);
}
const ProgramGraph &VoxelGraphFunction::get_graph() const {
return _graph;
}
void VoxelGraphFunction::register_subresource(Resource &resource) {
// print_line(String("{0}: Registering subresource {1}").format(varray(int64_t(this), int64_t(&resource))));
resource.connect(VoxelStringNames::get_singleton().changed,
ZN_GODOT_CALLABLE_MP(this, VoxelGraphFunction, _on_subresource_changed));
}
void VoxelGraphFunction::unregister_subresource(Resource &resource) {
// print_line(String("{0}: Unregistering subresource {1}").format(varray(int64_t(this), int64_t(&resource))));
resource.disconnect(VoxelStringNames::get_singleton().changed,
ZN_GODOT_CALLABLE_MP(this, VoxelGraphFunction, _on_subresource_changed));
}
void VoxelGraphFunction::register_subresources() {
_graph.for_each_node([this](ProgramGraph::Node &node) {
for (size_t i = 0; i < node.params.size(); ++i) {
Ref<Resource> resource = node.params[i];
if (resource.is_valid()) {
register_subresource(**resource);
}
}
});
}
void VoxelGraphFunction::unregister_subresources() {
_graph.for_each_node([this](ProgramGraph::Node &node) {
for (size_t i = 0; i < node.params.size(); ++i) {
Ref<Resource> resource = node.params[i];
if (resource.is_valid()) {
unregister_subresource(**resource);
}
}
});
}
void VoxelGraphFunction::_on_subresource_changed() {
emit_changed();
}
static Dictionary get_graph_as_variant_data(const ProgramGraph &graph) {
/*
{
"version": 2,
"nodes": {
"1": {
"type": "Name",
"gui_position": Vector2(10, 10),
"gui_size": Vector2(100, 50),
"name": "Hello",
"auto_connect": true,
"input1": 0.0,
"input2": 0.0,
...
"param1": 0.0,
"param2": 0.0,
...
"dynamic_inputs": [
["dyn1", 0.0],
["dyn2", 0.0],
...
]
},
"2": {
...
},
...
},
"connections": [
[1, 0, 2, 0],
[1, 0, 3, 1],
...
]
}
*/
Dictionary nodes_data;
graph.for_each_node_id([&graph, &nodes_data](uint32_t node_id) {
const ProgramGraph::Node *node = graph.try_get_node(node_id);
ERR_FAIL_COND(node == nullptr);
Dictionary node_data;
const NodeType &type = NodeTypeDB::get_singleton().get_type(node->type_id);
node_data["type"] = type.name;
node_data["gui_position"] = node->gui_position;
if (node->gui_size != Vector2()) {
node_data["gui_size"] = node->gui_size;
}
if (node->name != StringName()) {
node_data["name"] = node->name;
}
// Parameters
for (size_t j = 0; j < type.params.size(); ++j) {
const NodeType::Param ¶m = type.params[j];
node_data[param.name] = node->params[j];
}
if (node->autoconnect_default_inputs) {
node_data["auto_connect"] = true;
}
// Static default inputs
for (size_t j = 0; j < type.inputs.size(); ++j) {
if (node->inputs[j].connections.size() == 0) {
const NodeType::Port &port = type.inputs[j];
node_data[port.name] = node->default_inputs[j];
}
}
// Function default inputs
if (node->type_id == VoxelGraphFunction::NODE_FUNCTION) {
ZN_ASSERT(node->params.size() >= 1);
Ref<VoxelGraphFunction> function = node->params[0];
ZN_ASSERT_RETURN(function.is_valid());
Span<const VoxelGraphFunction::Port> inputs = function->get_input_definitions();
ZN_ASSERT_RETURN(inputs.size() == node->default_inputs.size());
for (unsigned int input_index = 0; input_index < inputs.size(); ++input_index) {
const VoxelGraphFunction::Port &input = inputs[input_index];
node_data[input.name] = node->default_inputs[input_index];
}
}
// Dynamic inputs. Order matters.
Array dynamic_inputs_data;
for (size_t j = 0; j < node->inputs.size(); ++j) {
const ProgramGraph::Port &port = node->inputs[j];
if (port.is_dynamic()) {
Array d;
d.resize(2);
d[0] = String(port.dynamic_name.c_str());
d[1] = node->default_inputs[j];
dynamic_inputs_data.append(d);
}
}
if (dynamic_inputs_data.size() > 0) {
node_data["dynamic_inputs"] = dynamic_inputs_data;
}
String key = String::num_uint64(node_id);
nodes_data[key] = node_data;
});
Array connections_data;
std::vector<ProgramGraph::Connection> connections;
graph.get_connections(connections);
connections_data.resize(connections.size());
for (size_t i = 0; i < connections.size(); ++i) {
const ProgramGraph::Connection &con = connections[i];
Array con_data;
con_data.resize(4);
con_data[0] = con.src.node_id;
con_data[1] = con.src.port_index;
con_data[2] = con.dst.node_id;
con_data[3] = con.dst.port_index;
connections_data[i] = con_data;
}
Dictionary data;
data["nodes"] = nodes_data;
data["connections"] = connections_data;
data["version"] = 2;
return data;
}
Dictionary VoxelGraphFunction::get_graph_as_variant_data() const {
return zylann::voxel::pg::get_graph_as_variant_data(_graph);
}
static bool var_to_id(Variant v, uint32_t &out_id, uint32_t min = 0) {
ERR_FAIL_COND_V(v.get_type() != Variant::INT, false);
const int i = v;
ERR_FAIL_COND_V(i < 0 || (unsigned int)i < min, false);
out_id = i;
return true;
}
static bool load_graph_from_variant_data(ProgramGraph &graph, Dictionary data, String resource_path) {
Dictionary nodes_data = data["nodes"];
Array connections_data = data["connections"];
const NodeTypeDB &type_db = NodeTypeDB::get_singleton();
// Can't iterate using `next()`, because in GDExtension, there doesn't seem to be a way to do so.
const Array nodes_data_keys = nodes_data.keys();
for (int nodes_data_key_index = 0; nodes_data_key_index < nodes_data_keys.size(); ++nodes_data_key_index) {
const Variant id_key = nodes_data_keys[nodes_data_key_index];
const String id_str = id_key;
ERR_FAIL_COND_V(!id_str.is_valid_int(), false);
const int sid = id_str.to_int();
ERR_FAIL_COND_V(sid < static_cast<int>(ProgramGraph::NULL_ID), false);
const uint32_t id = sid;
Dictionary node_data = nodes_data[id_key];
ERR_FAIL_COND_V(node_data.is_empty(), false);
const String type_name = node_data["type"];
const Vector2 gui_position = node_data["gui_position"];
VoxelGraphFunction::NodeTypeID type_id;
ERR_FAIL_COND_V(!type_db.try_get_type_id_from_name(type_name, type_id), false);
// Don't create default param values, they will be assigned from serialized data
ProgramGraph::Node *node = create_node_internal(graph, type_id, gui_position, id, false);
ERR_FAIL_COND_V(node == nullptr, false);
// TODO Graphs made in older versions must have autoconnect always off
node->gui_size = node_data.get("gui_size", Vector2());
if (type_id == VoxelGraphFunction::NODE_FUNCTION) {
const NodeType &ntype = type_db.get_type(type_id);
ZN_ASSERT(ntype.params.size() >= 1);
// The function reference is always the first parameter
const String func_key = ntype.params[0].name;
Ref<VoxelGraphFunction> function = node_data[func_key];
if (function.is_null()) {
ERR_PRINT(String("Unable to load external function referenced in {0} {}")
.format(varray(VoxelGraphFunction::get_class_static(), resource_path)));
// continue;
// Cancel, connections to that node cause crashes if we carry on loading. Perhaps we could try using a
// placeholder in the future so the graph can still be opened?
// We should also report the missing dependencies in the editor somehow, because Godot doesn't do it for
// us if the resource is opened in some cases
return false;
}
setup_function(*node, function);
// TODO Create a placeholder node in case a function isn't found to avoid loss of data?
// For now it's probably ok as long as the user doesn't save over
// TODO Function inputs are user-named, but they could conflict with other keys in this save format
}
Variant auto_connect_v = node_data.get("auto_connect", Variant());
if (auto_connect_v != Variant()) {
node->autoconnect_default_inputs = auto_connect_v;
}
// Can't iterate using `next()`, because in GDExtension, there doesn't seem to be a way to do so.
const Array node_data_keys = node_data.keys();
for (int node_data_key_index = 0; node_data_key_index < node_data_keys.size(); ++node_data_key_index) {
const Variant param_key = node_data_keys[node_data_key_index];
const String param_name = param_key;
if (param_name == "type") {
continue;
}
if (param_name == "gui_position") {
continue;
}
if (param_name == "gui_size") {
continue;
}
if (param_name == "auto_connect") {
continue;
}
if (param_name == "dynamic_inputs") {
const Array dynamic_inputs_data = node_data[param_key];
for (int dpi = 0; dpi < dynamic_inputs_data.size(); ++dpi) {
const Array d = dynamic_inputs_data[dpi];
ERR_FAIL_COND_V(d.size() != 2, false);
const String dynamic_param_name = d[0];
ProgramGraph::Port dport;
CharString dynamic_param_name_utf8 = dynamic_param_name.utf8();
dport.dynamic_name = dynamic_param_name_utf8.get_data();
const Variant defval = d[1];
node->default_inputs.push_back(defval);
node->inputs.push_back(dport);
}
continue;
}
uint32_t param_index;
if (type_db.try_get_param_index_from_name(type_id, param_name, param_index)) {
ERR_CONTINUE(param_index < 0 || param_index >= node->params.size());
node->params[param_index] = node_data[param_key];
}
if (type_db.try_get_input_index_from_name(type_id, param_name, param_index)) {
ERR_CONTINUE(param_index < 0 || param_index >= node->default_inputs.size());
node->default_inputs[param_index] = node_data[param_key];
}
const Variant vname = node_data.get("name", Variant());
if (vname != Variant()) {
node->name = vname;
}
}
}
for (int i = 0; i < connections_data.size(); ++i) {
Array con_data = connections_data[i];
ERR_FAIL_COND_V(con_data.size() != 4, false);
ProgramGraph::PortLocation src;
ProgramGraph::PortLocation dst;
ERR_FAIL_COND_V(!var_to_id(con_data[0], src.node_id, ProgramGraph::NULL_ID), false);
ERR_FAIL_COND_V(!var_to_id(con_data[1], src.port_index), false);
ERR_FAIL_COND_V(!var_to_id(con_data[2], dst.node_id, ProgramGraph::NULL_ID), false);
ERR_FAIL_COND_V(!var_to_id(con_data[3], dst.port_index), false);
// TODO Create temporary invalid connections if the node has different inputs than before (to handle the case
// where an external function has changed)
graph.connect(src, dst);
}
return true;
}
bool VoxelGraphFunction::load_graph_from_variant_data(Dictionary data) {
clear();
if (zylann::voxel::pg::load_graph_from_variant_data(_graph, data, get_path())) {
register_subresources();
return true;
} else {
_graph.clear();
return false;
}
}
void VoxelGraphFunction::get_node_input_info(
uint32_t node_id, unsigned int input_index, String *out_name, AutoConnect *out_autoconnect) const {
const ProgramGraph::Node &node = _graph.get_node(node_id);
ZN_ASSERT(input_index < node.inputs.size());
const ProgramGraph::Port &port = node.inputs[input_index];
if (out_name != nullptr) {
if (node.type_id == VoxelGraphFunction::NODE_FUNCTION) {
ZN_ASSERT(node.params.size() >= 1);
Ref<VoxelGraphFunction> func = node.params[0];