-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathunrealcpp.rs
More file actions
5629 lines (5136 loc) · 217 KB
/
unrealcpp.rs
File metadata and controls
5629 lines (5136 loc) · 217 KB
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
//! Autogenerated Unreal‑C++ code‑gen backend for SpacetimeDB CLI
use crate::code_indenter::CodeIndenter;
use crate::util::{
fmt_fn, iter_table_names_and_types, print_auto_generated_file_comment, print_auto_generated_version_comment,
};
use crate::util::{iter_indexes, iter_procedures, iter_reducers};
use crate::Lang;
use crate::OutputFile;
use convert_case::{Case, Casing};
use spacetimedb_lib::sats::layout::PrimitiveType;
use spacetimedb_schema::def::{BTreeAlgorithm, IndexAlgorithm};
use spacetimedb_schema::def::{ModuleDef, ReducerDef, TableDef, TypeDef};
use spacetimedb_schema::identifier::Identifier;
use spacetimedb_schema::schema::{Schema, TableSchema};
use spacetimedb_schema::type_for_generate::{
AlgebraicTypeDef, AlgebraicTypeUse, PlainEnumTypeDef, ProductTypeDef, SumTypeDef,
};
use std::collections::HashSet;
use std::fmt::{self};
use std::ops::Deref;
use std::path::Path;
pub struct UnrealCpp<'opts> {
pub module_name: &'opts str,
pub uproject_dir: &'opts Path,
pub module_prefix: &'opts str,
}
// ---------------------------------------------------------------------------
// Lang impl
// ---------------------------------------------------------------------------
impl UnrealCpp<'_> {
fn get_api_macro(&self) -> String {
format!("{}_API", self.module_name.to_uppercase())
}
}
impl Lang for UnrealCpp<'_> {
fn generate_table_file_from_schema(&self, module: &ModuleDef, table: &TableDef, schema: TableSchema) -> OutputFile {
let module_prefix = self.module_prefix;
let struct_name = type_ref_name(module_prefix, module, table.product_type_ref);
let table_pascal = format!("{module_prefix}{}", table.name.deref().to_case(Case::Pascal));
let self_header = table_pascal.clone() + "Table";
let mut output = UnrealCppAutogen::new(
&[
"Types/Builtins.h",
&format!("ModuleBindings/Types/{struct_name}Type.g.h"),
"Tables/RemoteTable.h",
"DBCache/WithBsatn.h",
"DBCache/TableHandle.h",
"DBCache/TableCache.h",
],
&self_header,
false,
);
let row_struct = format!("F{struct_name}Type"); // e.g. "FUserType", "FMessageType"
let handle_cls = format!("U{table_pascal}Table"); // "UMessageTable"
let table_name = table.name.deref().to_string();
// Generate unique index classes first
let product_type = module.typespace_for_generate()[table.product_type_ref].as_product();
let mut unique_indexes = Vec::new();
let mut multi_key_indexes = Vec::new();
for idx in iter_indexes(table) {
let Some(accessor_name) = idx.accessor_name.as_ref() else {
continue;
};
if let IndexAlgorithm::BTree(BTreeAlgorithm { columns }) = &idx.algorithm {
if schema.is_unique(columns) {
if let Some(col) = columns.as_singleton() {
let (f_name, f_ty) = &product_type.unwrap().elements[col.idx()];
let field_name = f_name.deref().to_case(Case::Pascal);
let field_type =
cpp_ty_fmt_with_module(self.module_prefix, module, f_ty, self.module_name).to_string();
let index_name = accessor_name.deref().to_case(Case::Pascal);
let index_class_name = format!("U{table_pascal}{index_name}UniqueIndex");
let key_type = field_type.clone();
let field_name_lowercase = field_name.to_lowercase();
writeln!(output, "UCLASS(Blueprintable)");
writeln!(
output,
"class {} {index_class_name} : public UObject",
self.get_api_macro()
);
writeln!(output, "{{");
writeln!(output, " GENERATED_BODY()");
writeln!(output);
writeln!(output, "private:");
writeln!(output, " // Declare an instance of your templated helper.");
writeln!(
output,
" // It's private because the UObject wrapper will expose its functionality."
);
writeln!(
output,
" FUniqueIndexHelper<{row_struct}, {key_type}, FTableCache<{row_struct}>> {index_name}IndexHelper;"
);
writeln!(output);
writeln!(output, "public:");
writeln!(output, " {index_class_name}()");
writeln!(
output,
" // Initialize the helper with the specific unique index name"
);
writeln!(output, " : {index_name}IndexHelper(\"{}\") {{", f_name.deref());
writeln!(output, " }}");
writeln!(output);
writeln!(output, " /**");
writeln!(
output,
" * Finds a {table_pascal} by their unique {field_name_lowercase}."
);
writeln!(output, " * @param Key The {field_name_lowercase} to search for.");
writeln!(
output,
" * @return The found {row_struct}, or a default-constructed {row_struct} if not found."
);
writeln!(output, " */");
// Only mark as BlueprintCallable if the key type is Blueprint-compatible
if is_blueprintable(module, f_ty) {
writeln!(
output,
" UFUNCTION(BlueprintCallable, Category = \"SpacetimeDB|{table_pascal}Index\")"
);
} else {
writeln!(
output,
" // NOTE: Not exposed to Blueprint because {key_type} types are not Blueprint-compatible"
);
}
writeln!(output, " {row_struct} Find({key_type} Key)");
writeln!(output, " {{");
writeln!(output, " // Simply delegate the call to the internal helper");
writeln!(output, " return {index_name}IndexHelper.FindUniqueIndex(Key);");
writeln!(output, " }}");
writeln!(output);
writeln!(
output,
" // A public setter to provide the cache to the helper after construction"
);
writeln!(output, " // This is a common pattern when the cache might be created or provided by another system.");
writeln!(
output,
" void SetCache(TSharedPtr<const FTableCache<{row_struct}>> In{table_pascal}Cache)"
);
writeln!(output, " {{");
writeln!(output, " {index_name}IndexHelper.Cache = In{table_pascal}Cache;");
writeln!(output, " }}");
writeln!(output, "}};");
writeln!(output, "/***/");
writeln!(output);
unique_indexes.push((index_name, index_class_name, field_type, f_name.deref().to_string()));
}
}
// Handle non-unique BTree indexes
else {
// Generate non-unique BTree index class
let _index_name = accessor_name.deref().to_case(Case::Pascal);
let index_class_name = format!("U{table_pascal}{_index_name}Index");
// Get column information
let column_info: Vec<_> = columns
.iter()
.map(|col| {
let (f_name, f_ty) = &product_type.unwrap().elements[col.idx()];
let field_name = f_name.deref().to_case(Case::Pascal);
let field_type =
cpp_ty_fmt_with_module(self.module_prefix, module, f_ty, self.module_name).to_string();
let param_type = format!("const {field_type}&");
(field_name, field_type, param_type, f_ty, f_name.deref().to_string())
})
.collect();
// Create filter method name by concatenating column names
let filter_method_name = format!(
"Filter{}",
column_info
.iter()
.map(|(name, _, _, _, _)| name.as_str())
.collect::<Vec<_>>()
.join("")
);
// Create parameter list for methods
let method_params = column_info
.iter()
.map(|(field_name, _, param_type, _, _)| format!("{param_type} {field_name}"))
.collect::<Vec<_>>()
.join(", ");
// Create parameter names for internal call
let param_names = column_info
.iter()
.map(|(field_name, _, _, _, _)| field_name.clone())
.collect::<Vec<_>>()
.join(", ");
// Create TTuple type for FindByMultiKeyBTreeIndex
let tuple_types = column_info
.iter()
.map(|(_, field_type, _, _, _)| field_type.clone())
.collect::<Vec<_>>()
.join(", ");
// This is a potential bug in the original code, but keeping it as is for now
// Originally Arvikasoft had if column_info.len() == 1 { format!("TTuple<{tuple_types}>"); } else { format!("TTuple<{tuple_types}>"); }
// This makes no sense since both branches are the same
let tuple_type = format!("TTuple<{tuple_types}>");
writeln!(output, "UCLASS(Blueprintable)");
writeln!(output, "class {index_class_name} : public UObject");
writeln!(output, "{{");
writeln!(output, " GENERATED_BODY()");
writeln!(output);
writeln!(output, "public:");
writeln!(output, " TArray<{row_struct}> Filter({method_params}) const");
writeln!(output, " {{");
writeln!(output, " TArray<{row_struct}> OutResults;");
writeln!(output);
writeln!(output, " LocalCache->FindByMultiKeyBTreeIndex<{tuple_type}>(");
writeln!(output, " OutResults,");
writeln!(output, " TEXT(\"{}\"),", accessor_name.deref());
writeln!(output, " MakeTuple({param_names})");
writeln!(output, " );");
writeln!(output);
writeln!(output, " return OutResults;");
writeln!(output, " }}");
writeln!(output);
writeln!(
output,
" void SetCache(TSharedPtr<FTableCache<{row_struct}>> InCache)"
);
writeln!(output, " {{");
writeln!(output, " LocalCache = InCache;");
writeln!(output, " }}");
writeln!(output);
writeln!(output, "private:");
// Check if all parameter types are Blueprint-compatible
let all_blueprintable = column_info
.iter()
.all(|(_, _, _, f_ty, _)| is_blueprintable(module, f_ty));
if all_blueprintable {
writeln!(output, " UFUNCTION(BlueprintCallable)");
} else {
writeln!(output, " // NOTE: Not exposed to Blueprint because some parameter types are not Blueprint-compatible");
}
writeln!(
output,
" void {filter_method_name}(TArray<{row_struct}>& OutResults, {method_params})"
);
writeln!(output, " {{");
writeln!(output, " OutResults = Filter({param_names});");
writeln!(output, " }}");
writeln!(output);
writeln!(output, " TSharedPtr<FTableCache<{row_struct}>> LocalCache;");
writeln!(output, "}};");
writeln!(output);
// Store information for PostInitialize generation
let property_name = accessor_name.deref().to_case(Case::Pascal);
multi_key_indexes.push((property_name, index_class_name));
}
}
}
writeln!(output, "UCLASS(BlueprintType)");
writeln!(
output,
"class {} {handle_cls} : public URemoteTable",
self.get_api_macro()
);
writeln!(output, "{{");
writeln!(output, " GENERATED_BODY()");
writeln!(output);
writeln!(output, "public:");
// Generate unique index properties
for (index_name, index_class_name, _, _) in &unique_indexes {
writeln!(output, " UPROPERTY(BlueprintReadOnly)");
writeln!(output, " {index_class_name}* {index_name};");
writeln!(output);
}
// Generate non-unique BTree index properties
for (index_name, index_class_name) in &multi_key_indexes {
writeln!(output, " UPROPERTY(BlueprintReadOnly)");
writeln!(output, " {index_class_name}* {};", index_name.to_case(Case::Pascal));
writeln!(output);
}
writeln!(output, " void PostInitialize();");
writeln!(output);
writeln!(output, " /** Update function for {table_name} table*/");
writeln!(
output,
" FTableAppliedDiff<{row_struct}> Update(TArray<FWithBsatn<{row_struct}>> InsertsRef, TArray<FWithBsatn<{row_struct}>> DeletesRef);"
);
writeln!(output);
writeln!(output, " /** Number of subscribed rows currently in the cache */");
writeln!(output, " UFUNCTION(BlueprintCallable, Category = \"SpacetimeDB\")");
writeln!(output, " int32 Count() const;");
writeln!(output);
writeln!(output, " /** Return all subscribed rows in the cache */");
writeln!(output, " UFUNCTION(BlueprintCallable, Category = \"SpacetimeDB\")");
writeln!(output, " TArray<{row_struct}> Iter() const;");
writeln!(output);
// Generate table events in public section
writeln!(output, " // Table Events");
writeln!(output, " DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams( ");
writeln!(output, " F{module_prefix}On{table_pascal}Insert,");
writeln!(output, " const F{module_prefix}EventContext&, Context,");
writeln!(output, " const {row_struct}&, NewRow);");
writeln!(output);
writeln!(output, " DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams( ");
writeln!(output, " F{module_prefix}On{table_pascal}Update,");
writeln!(output, " const F{module_prefix}EventContext&, Context,");
writeln!(output, " const {row_struct}&, OldRow,");
writeln!(output, " const {row_struct}&, NewRow);");
writeln!(output);
writeln!(output, " DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams( ");
writeln!(output, " F{module_prefix}On{table_pascal}Delete,");
writeln!(output, " const F{module_prefix}EventContext&, Context,");
writeln!(output, " const {row_struct}&, DeletedRow);");
writeln!(output);
writeln!(
output,
" UPROPERTY(BlueprintAssignable, Category = \"SpacetimeDB Events\")"
);
writeln!(output, " F{module_prefix}On{table_pascal}Insert OnInsert;");
writeln!(output);
writeln!(
output,
" UPROPERTY(BlueprintAssignable, Category = \"SpacetimeDB Events\")"
);
writeln!(output, " F{module_prefix}On{table_pascal}Update OnUpdate;");
writeln!(output);
writeln!(
output,
" UPROPERTY(BlueprintAssignable, Category = \"SpacetimeDB Events\")"
);
writeln!(output, " F{module_prefix}On{table_pascal}Delete OnDelete;");
writeln!(output);
writeln!(output, "private:");
writeln!(output, " const FString TableName = TEXT(\"{table_name}\");");
writeln!(output);
writeln!(output, " TSharedPtr<UClientCache<{row_struct}>> Data;");
writeln!(output, "}};"); // end UCLASS
OutputFile {
filename: format!(
"Source/{}/Public/ModuleBindings/Tables/{}{}Table.g.h",
self.module_name,
self.module_prefix,
table.name.deref().to_case(Case::Pascal) //type_ref_name(module, table.product_type_ref)
),
code: output.into_inner(),
}
}
fn generate_type_files(&self, module: &ModuleDef, typ: &TypeDef) -> Vec<OutputFile> {
let name = type_ref_name(self.module_prefix, module, typ.ty);
let filename = format!(
"Source/{}/Public/ModuleBindings/Types/{}Type.g.h",
self.module_name, &name
);
let code: String = match &module.typespace_for_generate()[typ.ty] {
AlgebraicTypeDef::PlainEnum(plain_enum) => autogen_cpp_enum(&name, plain_enum),
AlgebraicTypeDef::Product(product_type_def) => autogen_cpp_struct(
self.module_prefix,
module,
&name,
product_type_def,
&self.get_api_macro(),
self.module_name,
),
AlgebraicTypeDef::Sum(sum_type_def) => autogen_cpp_sum(
self.module_prefix,
module,
&name,
sum_type_def,
&self.get_api_macro(),
self.module_name,
),
};
vec![OutputFile { filename, code }]
}
fn generate_reducer_file(&self, module: &ModuleDef, reducer: &ReducerDef) -> OutputFile {
let reducer_original = reducer.name.deref();
let reducer_pascal = reducer_original.to_case(Case::Pascal);
let module_prefix = self.module_prefix;
let pascal = format!("{module_prefix}{reducer_pascal}");
// Collect includes for parameter types
let mut includes = HashSet::<String>::new();
for (_param_name, param_type) in &reducer.params_for_generate.elements {
collect_includes_for_type(module_prefix, module, param_type, &mut includes, self.module_name);
}
// Add ReducerBase.g.h for UReducerBase definition
includes.insert(format!("ModuleBindings/{module_prefix}ReducerBase.g.h"));
// Convert to sorted vector
let mut include_vec: Vec<String> = includes.into_iter().collect();
include_vec.sort();
// Convert to string references
let include_refs: Vec<&str> = include_vec.iter().map(|s| s.as_str()).collect();
let mut header = UnrealCppAutogen::new(&include_refs, &pascal, false);
let args_struct = format!("F{pascal}Args");
// Generate reducer arguments struct
writeln!(header, "// Reducer arguments struct for {pascal}");
writeln!(header, "USTRUCT(BlueprintType)");
writeln!(header, "struct {} {args_struct}", self.get_api_macro());
writeln!(header, "{{");
writeln!(header, " GENERATED_BODY()");
writeln!(header);
// Generate properties for each parameter
for (param_name, param_type) in &reducer.params_for_generate.elements {
let param_pascal = param_name.deref().to_case(Case::Pascal);
let type_str = cpp_ty_fmt_with_module(self.module_prefix, module, param_type, self.module_name).to_string();
let init_str = cpp_ty_init_fmt_impl(param_type, type_str.as_str());
let field_decl = format!("{type_str} {param_pascal}{init_str}");
// Check if the type is blueprintable
if is_blueprintable(module, param_type) {
writeln!(header, " UPROPERTY(BlueprintReadWrite, Category=\"SpacetimeDB\")");
} else {
// Add comment explaining why the field isn't exposed as UPROPERTY
writeln!(
header,
" // NOTE: {type_str} field not exposed to Blueprint due to non-blueprintable elements"
);
}
writeln!(header, " {field_decl};");
writeln!(header);
}
// Generate default constructor
writeln!(header, " {args_struct}() = default;");
writeln!(header);
// Generate parameterized constructor (for BSATN/internal use)
if !reducer.params_for_generate.elements.is_empty() {
write!(header, " {args_struct}(");
let mut first = true;
for (param_name, param_type) in &reducer.params_for_generate.elements {
if !first {
write!(header, ", ");
}
first = false;
let param_pascal = param_name.deref().to_case(Case::Pascal);
let type_str =
cpp_ty_fmt_with_module(self.module_prefix, module, param_type, self.module_name).to_string();
write!(header, "const {type_str}& In{param_pascal}");
}
writeln!(header, ")");
write!(header, " : ");
let mut first = true;
for (param_name, _) in &reducer.params_for_generate.elements {
if !first {
write!(header, ", ");
}
first = false;
let param_pascal = param_name.deref().to_case(Case::Pascal);
write!(header, "{param_pascal}(In{param_pascal})");
}
writeln!(header);
writeln!(header, " {{}}");
writeln!(header);
}
// Add operator== and operator!=
writeln!(header);
writeln!(
header,
" FORCEINLINE bool operator==(const {args_struct}& Other) const"
);
writeln!(header, " {{");
// Generate comparison for each field
let mut comparisons = Vec::new();
for (param_name, _) in &reducer.params_for_generate.elements {
let param_pascal = param_name.deref().to_case(Case::Pascal);
// For value types, direct comparison
comparisons.push(format!("{param_pascal} == Other.{param_pascal}"));
}
if comparisons.is_empty() {
writeln!(header, " return true;");
} else {
writeln!(header, " return {};", comparisons.join(" && "));
}
writeln!(header, " }}");
writeln!(
header,
" FORCEINLINE bool operator!=(const {args_struct}& Other) const"
);
writeln!(header, " {{");
writeln!(header, " return !(*this == Other);");
writeln!(header, " }}");
writeln!(header, "}};");
writeln!(header);
// Add BSATN serialization support for reducer args struct
writeln!(header, "namespace UE::SpacetimeDB");
writeln!(header, "{{");
// Generate the field list for the UE_SPACETIMEDB_STRUCT macro
let field_names: Vec<String> = reducer
.params_for_generate
.elements
.iter()
.map(|(name, _)| name.deref().to_case(Case::Pascal))
.collect();
if field_names.is_empty() {
writeln!(header, " UE_SPACETIMEDB_STRUCT_EMPTY({args_struct});");
} else {
writeln!(
header,
" UE_SPACETIMEDB_STRUCT({args_struct}, {});",
field_names.join(", ")
);
}
writeln!(header, "}}");
writeln!(header);
// Generate the reducer class
writeln!(header, "// Reducer class for internal dispatching");
writeln!(header, "UCLASS(BlueprintType)");
writeln!(
header,
"class {} U{pascal}Reducer : public U{module_prefix}ReducerBase",
self.get_api_macro()
);
writeln!(header, "{{");
writeln!(header, " GENERATED_BODY()");
writeln!(header);
writeln!(header, "public:");
// Generate properties for each parameter (for dispatching)
for (param_name, param_type) in &reducer.params_for_generate.elements {
let param_pascal = param_name.deref().to_case(Case::Pascal);
let type_str = cpp_ty_fmt_with_module(self.module_prefix, module, param_type, self.module_name).to_string();
let field_decl = format!("{type_str} {param_pascal}");
// Check if the type is blueprintable
if is_blueprintable(module, param_type) {
writeln!(header, " UPROPERTY(BlueprintReadOnly, Category=\"SpacetimeDB\")");
} else {
// Add comment explaining why the field isn't exposed as UPROPERTY
writeln!(
header,
" // NOTE: {type_str} field not exposed to Blueprint due to non-blueprintable elements"
);
}
writeln!(header, " {field_decl};");
}
if !reducer.params_for_generate.elements.is_empty() {
writeln!(header);
}
writeln!(header, "}};");
writeln!(header);
writeln!(header);
let module_name = &self.module_name;
OutputFile {
filename: format!("Source/{module_name}/Public/ModuleBindings/Reducers/{pascal}.g.h"),
code: header.into_inner(),
}
}
fn generate_procedure_file(
&self,
module: &ModuleDef,
procedure: &spacetimedb_schema::def::ProcedureDef,
) -> OutputFile {
let procedure_snake = procedure.name.deref();
let procedure_name = procedure_snake.to_case(Case::Pascal);
let pascal = format!("{}{}", self.module_prefix, procedure_name);
// Collect includes for parameter types
let mut includes = HashSet::<String>::new();
for (_param_name, param_type) in &procedure.params_for_generate.elements {
collect_includes_for_type(self.module_prefix, module, param_type, &mut includes, self.module_name);
}
collect_includes_for_type(
self.module_prefix,
module,
&procedure.return_type_for_generate,
&mut includes,
self.module_name,
);
// Convert to sorted vector
let mut include_vec: Vec<String> = includes.into_iter().collect();
include_vec.sort();
// Convert to string references
let include_refs: Vec<&str> = include_vec.iter().map(|s| s.as_str()).collect();
let mut header = UnrealCppAutogen::new(&include_refs, &pascal, false);
let args_struct = format!("F{pascal}Args");
// Generate procedure arguments struct
writeln!(header, "// Procedure arguments struct for {pascal}");
writeln!(header, "USTRUCT(BlueprintType)");
writeln!(header, "struct {} {args_struct}", self.get_api_macro());
writeln!(header, "{{");
writeln!(header, " GENERATED_BODY()");
writeln!(header);
// Generate properties for each parameter
for (param_name, param_type) in &procedure.params_for_generate.elements {
let param_pascal = param_name.deref().to_case(Case::Pascal);
let type_str = cpp_ty_fmt_with_module(self.module_prefix, module, param_type, self.module_name).to_string();
let init_str = cpp_ty_init_fmt_impl(param_type, type_str.as_str());
let field_decl = format!("{type_str} {param_pascal}{init_str}");
// Check if the type is blueprintable
if is_blueprintable(module, param_type) {
writeln!(header, " UPROPERTY(BlueprintReadWrite, Category=\"SpacetimeDB\")");
} else {
// Add comment explaining why the field isn't exposed as UPROPERTY
writeln!(
header,
" // NOTE: {type_str} field not exposed to Blueprint due to non-blueprintable elements"
);
}
writeln!(header, " {field_decl};");
writeln!(header);
}
// Generate default constructor
writeln!(header, " {args_struct}() = default;");
writeln!(header);
// Generate parameterized constructor (for BSATN/internal use)
if !procedure.params_for_generate.elements.is_empty() {
write!(header, " {args_struct}(");
let mut first = true;
for (param_name, param_type) in &procedure.params_for_generate.elements {
if !first {
write!(header, ", ");
}
first = false;
let param_pascal = param_name.deref().to_case(Case::Pascal);
let type_str =
cpp_ty_fmt_with_module(self.module_prefix, module, param_type, self.module_name).to_string();
write!(header, "const {type_str}& In{param_pascal}");
}
writeln!(header, ")");
write!(header, " : ");
let mut first = true;
for (param_name, _) in &procedure.params_for_generate.elements {
if !first {
write!(header, ", ");
}
first = false;
let param_pascal = param_name.deref().to_case(Case::Pascal);
write!(header, "{param_pascal}(In{param_pascal})");
}
writeln!(header);
writeln!(header, " {{}}");
writeln!(header);
}
// Add operator== and operator!=
writeln!(header);
writeln!(
header,
" FORCEINLINE bool operator==(const {args_struct}& Other) const"
);
writeln!(header, " {{");
// Generate comparison for each field
let mut comparisons = Vec::new();
for (param_name, _) in &procedure.params_for_generate.elements {
let param_pascal = param_name.deref().to_case(Case::Pascal);
// For value types, direct comparison
comparisons.push(format!("{param_pascal} == Other.{param_pascal}"));
}
if comparisons.is_empty() {
writeln!(header, " return true;");
} else {
writeln!(header, " return {};", comparisons.join(" && "));
}
writeln!(header, " }}");
writeln!(
header,
" FORCEINLINE bool operator!=(const {args_struct}& Other) const"
);
writeln!(header, " {{");
writeln!(header, " return !(*this == Other);");
writeln!(header, " }}");
writeln!(header, "}};");
writeln!(header);
// Add BSATN serialization support for procedure args struct
writeln!(header, "namespace UE::SpacetimeDB");
writeln!(header, "{{");
// Generate the field list for the UE_SPACETIMEDB_STRUCT macro
let field_names: Vec<String> = procedure
.params_for_generate
.elements
.iter()
.map(|(name, _)| name.deref().to_case(Case::Pascal))
.collect();
if field_names.is_empty() {
writeln!(header, " UE_SPACETIMEDB_STRUCT_EMPTY({args_struct});");
} else {
writeln!(
header,
" UE_SPACETIMEDB_STRUCT({args_struct}, {});",
field_names.join(", ")
);
}
writeln!(header, "}}");
OutputFile {
filename: format!(
"Source/{}/Public/ModuleBindings/Procedures/{}.g.h",
self.module_name, pascal
),
code: header.into_inner(),
}
}
fn generate_global_files(&self, module: &ModuleDef) -> Vec<OutputFile> {
let mut files: Vec<OutputFile> = vec![];
let module_prefix = self.module_prefix;
// First, we need to confirm this module has the required base files
// Unreal works on the idea of modules added to the .uproject Source folder and described in the .uproject file
// To have the module build these files must exist
let source_dir = self.uproject_dir.join("Source").join(self.module_name);
let required_files = [
(
format!("{}.Build.cs", self.module_name),
generate_build_cs_content(self.module_name),
),
(
format!("{}.cpp", self.module_name),
generate_module_cpp_content(self.module_name),
),
(
format!("{}.h", self.module_name),
generate_module_h_content(self.module_name),
),
];
for (filename, content) in required_files {
let file_path = source_dir.join(&filename);
if !file_path.exists() {
files.push(OutputFile {
filename: format!("Source/{}/{}", self.module_name, filename),
code: content,
});
}
}
// We also need to ensure the .uproject file includes this module
let _ = ensure_module_in_uproject(self.uproject_dir, self.module_name);
// Second, collect and generate all optional types
let optional_types = collect_optional_types(self.module_prefix, module);
for optional_name in optional_types {
let module_name = &self.module_name;
let module_name_pascal = module_name.to_case(Case::Pascal);
let filename =
format!("Source/{module_name}/Public/ModuleBindings/Optionals/{module_name_pascal}{optional_name}.g.h");
let content = generate_optional_type(
&optional_name,
self.module_prefix,
module,
&self.get_api_macro(),
self.module_name,
);
files.push(OutputFile {
filename,
code: content,
});
}
// Generate the main SpacetimeDBClient file with proper manual includes
let mut includes = HashSet::<String>::new();
// Add base includes
includes.insert("Connection/DbConnectionBase.h".to_string());
includes.insert("Connection/DbConnectionBuilder.h".to_string());
includes.insert("Connection/Subscription.h".to_string());
includes.insert("Connection/SetReducerFlags.h".to_string());
includes.insert("Connection/Callback.h".to_string());
includes.insert(format!("ModuleBindings/{module_prefix}ReducerBase.g.h"));
includes.insert("Kismet/BlueprintFunctionLibrary.h".to_string());
// Include reducers
for reducer in iter_reducers(module) {
let reducer_pascal = format!("{module_prefix}{}", reducer.name.deref().to_case(Case::Pascal));
includes.insert(format!("ModuleBindings/Reducers/{reducer_pascal}.g.h"));
}
// Include procedures
for procedure in iter_procedures(module) {
let procedure_pascal = format!("{}{}", module_prefix, procedure.name.deref().to_case(Case::Pascal));
includes.insert(format!("ModuleBindings/Procedures/{procedure_pascal}.g.h"));
}
// Collect includes for types used in delegates and contexts
// FSpacetimeDBIdentity is used in F{module_prefix}OnConnectDelegate and context methods
collect_includes_for_type(
self.module_prefix,
module,
&AlgebraicTypeUse::Identity,
&mut includes,
self.module_name,
);
// FSpacetimeDBConnectionId is used in context methods
collect_includes_for_type(
self.module_prefix,
module,
&AlgebraicTypeUse::ConnectionId,
&mut includes,
self.module_name,
);
// Collect includes for all reducer parameter types
for reducer in iter_reducers(module) {
for (_param_name, param_type) in &reducer.params_for_generate.elements {
collect_includes_for_type(module_prefix, module, param_type, &mut includes, self.module_name);
}
}
// Collect includes for all procedure parameter types
for procedure in iter_procedures(module) {
for (_param_name, param_type) in &procedure.params_for_generate.elements {
collect_includes_for_type(module_prefix, module, param_type, &mut includes, self.module_name);
}
collect_includes_for_type(
module_prefix,
module,
&procedure.return_type_for_generate,
&mut includes,
self.module_name,
);
}
// Convert to sorted vector
let mut include_vec: Vec<String> = includes.into_iter().collect();
include_vec.sort();
// Convert to string references
let include_refs: Vec<&str> = include_vec.iter().map(|s| s.as_str()).collect();
let self_header = format!("{module_prefix}SpacetimeDBClient");
let mut client_h = UnrealCppAutogen::new(&include_refs, self_header.as_str(), true);
// Forward declarations
writeln!(client_h, "// Forward declarations");
writeln!(client_h, "class U{module_prefix}DbConnection;");
writeln!(client_h, "class U{module_prefix}RemoteTables;");
writeln!(client_h, "class U{module_prefix}RemoteReducers;");
writeln!(client_h, "class U{module_prefix}URemoteProcedures;");
writeln!(client_h, "class U{module_prefix}SubscriptionBuilder;");
writeln!(client_h, "class U{module_prefix}SubscriptionHandle;");
writeln!(client_h);
writeln!(client_h, "/** Forward declaration for tables */");
for (table_name, _) in iter_table_names_and_types(module) {
writeln!(
client_h,
"class U{module_prefix}{}Table;",
table_name.deref().to_case(Case::Pascal)
);
}
writeln!(client_h, "/***/");
writeln!(client_h);
// Delegates first (as in manual)
generate_delegates(&mut client_h, module_prefix);
// Context structs
generate_context_structs(
&mut client_h,
self.module_prefix,
module,
&self.get_api_macro(),
&self.module_name.to_case(Case::Pascal),
);
// SetReducerFlags class - inherits from USetReducerFlagsBase
writeln!(client_h, "UCLASS(BlueprintType)");
writeln!(
client_h,
"class {} U{module_prefix}SetReducerFlags : public USetReducerFlagsBase",
self.get_api_macro()
);
writeln!(client_h, "{{");
writeln!(client_h, "\tGENERATED_BODY()");
writeln!(client_h);
writeln!(client_h, "public:");
for reducer in iter_reducers(module) {
let reducer_name = reducer.name.deref().to_case(Case::Pascal);
writeln!(client_h, "\tUFUNCTION(BlueprintCallable, Category = \"SpacetimeDB\")");
writeln!(client_h, "\tvoid {reducer_name}(ECallReducerFlags Flag);");
}
writeln!(client_h);
writeln!(client_h, "}};");
writeln!(client_h);
// RemoteTables class
generate_remote_tables_class(&mut client_h, module_prefix, module, &self.get_api_macro());
// RemoteReducers class
generate_remote_reducers_class(
&mut client_h,
module_prefix,
module,
&self.get_api_macro(),
self.module_name,
);
// RemoteProcedures class
generate_remote_procedures_class(
&mut client_h,
module,
&self.get_api_macro(),
self.module_name,
self.module_prefix,
);
// SubscriptionBuilder class
generate_subscription_builder_class(&mut client_h, module_prefix, &self.get_api_macro());
// SubscriptionHandle class
generate_subscription_handle_class(&mut client_h, module_prefix, &self.get_api_macro());
// DbConnectionBuilder class
generate_db_connection_builder_class(&mut client_h, module_prefix, &self.get_api_macro());
// Main DbConnection class
generate_db_connection_class(
&mut client_h,
module_prefix,
module,
&self.get_api_macro(),
self.module_name,