-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.rs
More file actions
1204 lines (1079 loc) · 40.9 KB
/
build.rs
File metadata and controls
1204 lines (1079 loc) · 40.9 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
use std::env;
use std::fs;
use std::path::Path;
fn main() {
println!("cargo:rerun-if-changed=assets/data");
let out_dir = env::var("OUT_DIR").unwrap();
// Load all TOML data from assets/data/
let game_data = load_game_data();
// Generate items
generate_items(&out_dir, &game_data);
// Generate blocks
generate_blocks(&out_dir, &game_data);
// Generate block-item mappings
generate_block_mappings(&out_dir, &game_data);
// Generate recipes
generate_recipes(&out_dir, &game_data);
}
/// Loads and merges all TOML files from assets/data/ directory
fn load_game_data() -> toml::Table {
let data_dir = Path::new("assets/data");
let mut merged_table = toml::Table::new();
// Read all .toml files in the directory
let entries = fs::read_dir(data_dir)
.expect("Failed to read assets/data directory")
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("toml"))
.collect::<Vec<_>>();
// Sort by filename for deterministic order
let mut entries = entries;
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
let file_name = path.file_name().unwrap().to_string_lossy();
println!("cargo:rerun-if-changed={}", path.display());
let content = fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("Failed to read {}: {}", file_name, e));
let table: toml::Table = toml::from_str(&content)
.unwrap_or_else(|e| panic!("Failed to parse {}: {}", file_name, e));
// Merge tables
for (key, value) in table {
if merged_table.contains_key(&key) {
// If the key already exists and both are tables, merge them
if let (Some(existing_table), toml::Value::Table(new_table)) = (
merged_table.get_mut(&key).and_then(|v| v.as_table_mut()),
&value,
) {
for (sub_key, sub_value) in new_table {
existing_table.insert(sub_key.clone(), sub_value.clone());
}
} else {
panic!("Conflicting key '{}' in TOML files", key);
}
} else {
merged_table.insert(key, value);
}
}
}
merged_table
}
fn generate_items(out_dir: &str, game_data: &toml::Table) {
let dest_path = Path::new(&out_dir).join("generated_items.rs");
let items = game_data
.get("items")
.and_then(|v| v.as_table())
.expect("Missing [items] table in game data");
let mut enum_variants = Vec::new();
let mut name_match_arms = Vec::new();
let mut weight_match_arms = Vec::new();
let mut from_str_match_arms = Vec::new();
let mut all_items = Vec::new();
let mut texture_match_arms = Vec::new();
for (key, value) in items.iter() {
let table = value.as_table().expect("Item must be a table");
let variant_name = to_pascal_case(key);
let item_name = table.get("name").and_then(|v| v.as_str()).unwrap_or(key);
let weight = table
.get("weight")
.and_then(|v| {
if let Some(f) = v.as_float() {
Some(f)
} else if let Some(i) = v.as_integer() {
Some(i as f64)
} else {
None
}
})
.unwrap_or(1.0);
// Get optional image field, default to items.{itemname}
let texture_path = if let Some(image) = table.get("image").and_then(|v| v.as_str()) {
// Parse path like "tools.steel_pickaxe" or "items.stone"
format!("textures.{}", image)
} else {
// Default to textures.items.{key}
format!("textures.items.{}", key)
};
enum_variants.push(format!(" {},", variant_name));
name_match_arms.push(format!(
" ItemType::{} => \"{}\",",
variant_name, item_name
));
weight_match_arms.push(format!(
" ItemType::{} => {:.1},",
variant_name, weight
));
from_str_match_arms.push(format!(
" \"{}\" => Some(ItemType::{}),",
key.to_lowercase(),
variant_name
));
all_items.push(format!(" ItemType::{},", variant_name));
texture_match_arms.push(format!(
" ItemType::{} => &{},",
variant_name, texture_path
));
}
let generated_code = format!(
r#"#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ItemType {{
{}
}}
impl ItemType {{
pub fn name(&self) -> &'static str {{
match self {{
{}
}}
}}
pub fn weight(&self) -> f32 {{
match self {{
{}
}}
}}
pub fn from_str(s: &str) -> Option<Self> {{
match s.to_lowercase().as_str() {{
{}
_ => None,
}}
}}
pub fn all() -> &'static [ItemType] {{
&[
{}
]
}}
/// Returns the texture for this item from the TextureManager.
/// The texture path can be customized in items.toml with the 'image' field.
/// By default, uses textures.items.{{itemname}}
pub fn get_texture<'a>(&self, textures: &'a crate::TextureManager) -> &'a raylib::prelude::Texture2D {{
match self {{
{}
}}
}}
}}
"#,
enum_variants.join("\n"),
name_match_arms.join("\n"),
weight_match_arms.join("\n"),
from_str_match_arms.join("\n"),
all_items.join("\n"),
texture_match_arms.join("\n")
);
fs::write(&dest_path, generated_code).expect("Failed to write generated items");
}
fn generate_blocks(out_dir: &str, game_data: &toml::Table) {
let dest_path = Path::new(&out_dir).join("generated_blocks.rs");
let blocks = game_data
.get("blocks")
.and_then(|v| v.as_table())
.expect("Missing [blocks] table in game data");
let ores = game_data.get("ore").and_then(|v| v.as_table());
let mut enum_variants = Vec::new();
let mut name_match_arms = Vec::new();
let mut durability_match_arms = Vec::new();
let mut drops_match_arms = Vec::new();
let mut key_match_arms = Vec::new();
let mut from_str_match_arms = Vec::new();
let mut is_solid_match_arms = Vec::new();
let mut is_transparent_match_arms = Vec::new();
let mut is_liquid_match_arms = Vec::new();
let mut is_spike_match_arms = Vec::new();
let mut is_ladder_match_arms = Vec::new();
let mut is_pickup_match_arms = Vec::new();
let mut all_blocks = Vec::new();
let mut texture_match_arms = Vec::new();
let mut ore_spawn_match_arms = Vec::new();
let mut width_match_arms = Vec::new();
let mut height_match_arms = Vec::new();
let mut is_multi_tile_match_arms = Vec::new();
for (key, value) in blocks.iter() {
let table = value.as_table().expect("Block must be a table");
let variant_name = to_pascal_case(key);
let block_name = table.get("name").and_then(|v| v.as_str()).unwrap_or(key);
let block_type = table
.get("type")
.and_then(|v| v.as_str())
.unwrap_or("solid");
let durability = table
.get("durability")
.and_then(|v| {
if let Some(f) = v.as_float() {
Some(f)
} else if let Some(i) = v.as_integer() {
Some(i as f64)
} else {
None
}
})
.unwrap_or(1.0);
enum_variants.push(format!(" {},", variant_name));
name_match_arms.push(format!(
" Block::{} => \"{}\",",
variant_name, block_name
));
durability_match_arms.push(format!(
" Block::{} => {:.1},",
variant_name, durability
));
key_match_arms.push(format!(
" Block::{} => Some(\"{}\"),",
variant_name, key
));
from_str_match_arms.push(format!(
" \"{}\" => Some(Block::{}),",
key.to_lowercase(),
variant_name
));
// Generate drops match arm
if let Some(drops_str) = table.get("drops").and_then(|v| v.as_str()) {
let amount = table
.get("amount")
.and_then(|v| v.as_integer())
.unwrap_or(1);
drops_match_arms.push(format!(
" Block::{} => Some((crate::inventory::ItemType::from_str(\"{}\")?, {})),",
variant_name, drops_str, amount
));
} else {
drops_match_arms.push(format!(" Block::{} => None,", variant_name));
}
// Generate type check match arms based on block_type
match block_type {
"solid" => {
is_solid_match_arms.push(format!(" Block::{} => true,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => false,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => false,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => false,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => false,", variant_name));
}
"transparent" => {
is_solid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => true,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => false,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => false,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => false,", variant_name));
}
"liquid" => {
is_solid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => false,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => true,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => false,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => false,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => false,", variant_name));
}
"spike" => {
is_solid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => false,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => true,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => false,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => false,", variant_name));
}
"ladder" => {
is_solid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => false,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => false,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => true,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => false,", variant_name));
}
"air" => {
is_solid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => false,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => false,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => false,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => false,", variant_name));
}
"pickup" => {
is_solid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_transparent_match_arms.push(format!(" Block::{} => false,", variant_name));
is_liquid_match_arms.push(format!(" Block::{} => false,", variant_name));
is_spike_match_arms.push(format!(" Block::{} => false,", variant_name));
is_ladder_match_arms.push(format!(" Block::{} => false,", variant_name));
is_pickup_match_arms.push(format!(" Block::{} => true,", variant_name));
}
_ => panic!("Unknown block type '{}' for block '{}'", block_type, key),
}
all_blocks.push(format!(" Block::{},", variant_name));
// Parse width and height (default to 1)
let width = table.get("width").and_then(|v| v.as_integer()).unwrap_or(1) as usize;
let height = table
.get("height")
.and_then(|v| v.as_integer())
.unwrap_or(1) as usize;
width_match_arms.push(format!(" Block::{} => {},", variant_name, width));
height_match_arms.push(format!(
" Block::{} => {},",
variant_name, height
));
let is_multi = width > 1 || height > 1;
is_multi_tile_match_arms.push(format!(
" Block::{} => {},",
variant_name, is_multi
));
// Check if this block has ore spawn data
let has_ore_data = ores.as_ref().and_then(|o| o.get(key)).is_some();
if has_ore_data {
let ore_table = ores.as_ref().unwrap().get(key).unwrap().as_table().unwrap();
let spawns_from = ore_table
.get("spawns_from")
.and_then(|v| v.as_integer())
.unwrap_or(0);
let spawns_peak = ore_table
.get("spawns_peak")
.and_then(|v| v.as_integer())
.unwrap_or(100);
let spawns_to = ore_table
.get("spawns_to")
.and_then(|v| v.as_integer())
.unwrap_or(200);
let spawns_pap = ore_table
.get("spawns_pap")
.and_then(|v| {
if let Some(f) = v.as_float() {
Some(f)
} else if let Some(i) = v.as_integer() {
Some(i as f64)
} else {
None
}
})
.unwrap_or(1.0);
let min_vein_size = ore_table
.get("min_vein_size")
.and_then(|v| v.as_integer())
.unwrap_or(2);
let max_vein_size = ore_table
.get("max_vein_size")
.and_then(|v| v.as_integer())
.unwrap_or(6);
ore_spawn_match_arms.push(format!(
" Block::{} => Some(OreSpawnData {{ spawns_from: {}, spawns_peak: {}, spawns_to: {}, spawns_pap: {:.1}, min_vein_size: {}, max_vein_size: {} }}),",
variant_name, spawns_from, spawns_peak, spawns_to, spawns_pap, min_vein_size, max_vein_size
));
} else {
ore_spawn_match_arms.push(format!(" Block::{} => None,", variant_name));
}
// Generate texture match arm
if let Some(image_str) = table.get("image").and_then(|v| v.as_str()) {
// Parse path like "tiles.dirt" or "items.stone"
let texture_path = format!("textures.{}", image_str);
texture_match_arms.push(format!(
" Block::{} => &{},",
variant_name, texture_path
));
} else {
// Default to fallback texture
texture_match_arms.push(format!(
" Block::{} => &textures.tiles.{},",
variant_name, key
));
}
}
let generated_code = format!(
r#"// Generated block definitions
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Block {{
{}
}}
/// Ore spawn configuration data
#[derive(Debug, Clone, Copy)]
pub struct OreSpawnData {{
pub spawns_from: i32,
pub spawns_peak: i32,
pub spawns_to: i32,
pub spawns_pap: f32,
pub min_vein_size: i32,
pub max_vein_size: i32,
}}
impl Block {{
pub fn name(self) -> &'static str {{
match self {{
{}
}}
}}
pub fn durability(self) -> f32 {{
match self {{
{}
}}
}}
/// Returns the lowercase key used in blocks.toml for this block.
pub fn key(self) -> Option<&'static str> {{
match self {{
{}
}}
}}
pub fn from_str(s: &str) -> Option<Self> {{
match s.to_lowercase().as_str() {{
{}
_ => None,
}}
}}
/// Returns (item_type, amount) that this block drops when mined
pub fn get_drops(self) -> Option<(crate::inventory::ItemType, u32)> {{
match self {{
{}
}}
}}
pub fn is_solid(self) -> bool {{
match self {{
{}
}}
}}
pub fn is_transparent(self) -> bool {{
match self {{
{}
}}
}}
pub fn is_liquid(self) -> bool {{
match self {{
{}
}}
}}
pub fn is_spike(self) -> bool {{
match self {{
{}
}}
}}
pub fn is_ladder(self) -> bool {{
match self {{
{}
}}
}}
pub fn is_pickup(self) -> bool {{
match self {{
{}
}}
}}
pub fn all() -> &'static [Block] {{
&[
{}
]
}}
/// Returns the texture for this block from the TextureManager.
/// The texture path can be customized in blocks.toml with the 'image' field.
/// By default, uses the fallback texture.
pub fn get_texture<'a>(self, textures: &'a crate::TextureManager) -> &'a raylib::prelude::Texture2D {{
match self {{
{}
}}
}}
/// Returns the ore spawn data for this block, if it's an ore.
/// Configured in blocks.toml under [ore.blockname] sections.
pub fn get_ore_spawn_data(self) -> Option<OreSpawnData> {{
match self {{
{}
}}
}}
/// Returns the width of this block in tiles (default 1)
pub fn width(self) -> usize {{
match self {{
{}
}}
}}
/// Returns the height of this block in tiles (default 1)
pub fn height(self) -> usize {{
match self {{
{}
}}
}}
/// Returns true if this block occupies multiple tiles
pub fn is_multi_tile(self) -> bool {{
match self {{
{}
}}
}}
}}
"#,
enum_variants.join("\n"),
name_match_arms.join("\n"),
durability_match_arms.join("\n"),
key_match_arms.join("\n"),
from_str_match_arms.join("\n"),
drops_match_arms.join("\n"),
is_solid_match_arms.join("\n"),
is_transparent_match_arms.join("\n"),
is_liquid_match_arms.join("\n"),
is_spike_match_arms.join("\n"),
is_ladder_match_arms.join("\n"),
is_pickup_match_arms.join("\n"),
all_blocks.join("\n"),
texture_match_arms.join("\n"),
ore_spawn_match_arms.join("\n"),
width_match_arms.join("\n"),
height_match_arms.join("\n"),
is_multi_tile_match_arms.join("\n")
);
fs::write(&dest_path, generated_code).expect("Failed to write generated blocks");
}
fn generate_block_mappings(out_dir: &str, game_data: &toml::Table) {
let items = game_data
.get("items")
.and_then(|v| v.as_table())
.expect("Missing [items] table in game data");
let blocks = game_data
.get("blocks")
.and_then(|v| v.as_table())
.expect("Missing [blocks] table in game data");
// Get all block-type items
let mut block_items: std::collections::HashMap<String, String> =
std::collections::HashMap::new();
for (key, value) in items.iter() {
let table = value.as_table().expect("Item must be a table");
if let Some(item_type) = table.get("type").and_then(|v| v.as_str()) {
if item_type == "block" {
block_items.insert(key.clone(), to_pascal_case(key));
}
}
}
// Generate Block::to_item_type() match arms (only for blocks that have items)
let mut block_to_item_arms = Vec::new();
for block_key in blocks.keys() {
let variant = to_pascal_case(block_key);
if block_items.contains_key(block_key) {
block_to_item_arms.push(format!(
" Block::{} => Some(ItemType::{}),",
variant, variant
));
} else {
block_to_item_arms.push(format!(" Block::{} => None,", variant));
}
}
// Generate ItemType::to_block() match arms
let mut item_to_block_arms = Vec::new();
for variant in block_items.values() {
item_to_block_arms.push(format!(
" ItemType::{} => Some(Block::{}),",
variant, variant
));
}
// Generate the block mappings file
let block_mappings_code = format!(
r#"// Generated block-item mappings
impl Block {{
/// Converts a block to its corresponding item type, if it has one.
/// Some blocks (like Air, Water, Lava) don't have corresponding items.
pub fn to_item_type(self) -> Option<ItemType> {{
match self {{
{}
}}
}}
pub fn from_item_type(item: ItemType) -> Option<Block> {{
item.to_block()
}}
}}
impl ItemType {{
/// Converts an item to its corresponding block, if it's a block-type item.
#[allow(unreachable_patterns)]
pub fn to_block(self) -> Option<Block> {{
match self {{
{}
_ => None,
}}
}}
}}
"#,
block_to_item_arms.join("\n"),
item_to_block_arms.join("\n")
);
let block_mappings_path = Path::new(&out_dir).join("generated_block_mappings.rs");
fs::write(&block_mappings_path, block_mappings_code)
.expect("Failed to write generated block mappings");
}
fn to_pascal_case(s: &str) -> String {
s.split('_')
.map(|word| {
let mut chars = word.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().chain(chars).collect(),
}
})
.collect()
}
fn process_recipe(
key: &str,
value: &toml::Value,
available_items: &std::collections::HashSet<String>,
classify_io: &dyn Fn(&str) -> String,
recipe_definitions: &mut Vec<String>,
skipped_recipes: &mut Vec<String>,
) {
let table = value.as_table().expect("Recipe must be a table");
let recipe_type = table
.get("type")
.and_then(|v| v.as_str())
.expect(&format!("Recipe {} missing 'type' field", key));
let output = table
.get("output")
.and_then(|v| v.as_str())
.expect(&format!("Recipe {} missing 'output' field", key));
let output_amount = table
.get("amount")
.and_then(|v| v.as_integer())
.unwrap_or(1) as u32;
let inputs = table
.get("inputs")
.and_then(|v| v.as_array())
.expect(&format!("Recipe {} missing 'inputs' field", key));
// Classify output
let output_classification = classify_io(output);
if output_classification == "unknown" {
skipped_recipes.push(format!("{} (output '{}' not recognized)", key, output));
return;
}
// Generate input definitions
let mut input_defs = Vec::new();
for input in inputs {
let input_table = input.as_table().expect("Input must be a table");
let input_type = input_table
.get("type")
.and_then(|v| v.as_str())
.expect("Input missing 'type' field");
let input_amount = input_table
.get("amount")
.and_then(|v| v.as_integer())
.unwrap_or(1) as u32;
let input_classification = classify_io(input_type);
if input_classification == "unknown" {
skipped_recipes.push(format!("{} (input '{}' not recognized)", key, input_type));
return;
}
let input_normalized = input_type.replace(" ", "_");
match input_classification.as_str() {
"item" => {
let input_item = to_pascal_case(&input_normalized);
input_defs.push(format!(
"RecipeIOType::Item {{ item_type: ItemType::{}, amount: {} }}",
input_item, input_amount
));
}
"tool_pickaxe" => {
input_defs.push(format!(
"RecipeIOType::ToolPickaxe {{ level: \"{}\" }}",
input_normalized
));
}
"tool_dash" => {
input_defs.push(format!(
"RecipeIOType::ToolDash {{ level: \"{}\" }}",
input_normalized
));
}
"tool_glider" => {
input_defs.push(format!(
"RecipeIOType::ToolGlider {{ level: \"{}\" }}",
input_normalized
));
}
"tool_tideclock" => {
input_defs.push("RecipeIOType::ToolTideClock".to_string());
}
_ => {}
}
}
let recipe_type_enum = match recipe_type {
"always" => "RecipeType::Always",
"workbench" => "RecipeType::Workbench",
"furnace" => "RecipeType::Furnace",
"anvil" => "RecipeType::Anvil",
_ => panic!("Unknown recipe type: {}", recipe_type),
};
// Generate output definition
let output_normalized = output.replace(" ", "_");
let output_def = match output_classification.as_str() {
"item" => {
let output_item = to_pascal_case(&output_normalized);
format!(
"RecipeIOType::Item {{ item_type: ItemType::{}, amount: {} }}",
output_item, output_amount
)
}
"tool_pickaxe" => {
format!(
"RecipeIOType::ToolPickaxe {{ level: \"{}\" }}",
output_normalized
)
}
"tool_dash" => {
format!(
"RecipeIOType::ToolDash {{ level: \"{}\" }}",
output_normalized
)
}
"tool_glider" => {
format!(
"RecipeIOType::ToolGlider {{ level: \"{}\" }}",
output_normalized
)
}
"tool_tideclock" => "RecipeIOType::ToolTideClock".to_string(),
_ => return,
};
recipe_definitions.push(format!(
r#" Recipe {{
name: "{}",
recipe_type: {},
inputs: &[{}],
output: {},
}}"#,
key,
recipe_type_enum,
input_defs.join(", "),
output_def
));
}
fn generate_recipes(out_dir: &str, game_data: &toml::Table) {
let dest_path = Path::new(&out_dir).join("generated_recipes.rs");
// Get both regular recipes and tool recipes
let recipes = game_data.get("recipes").and_then(|v| v.as_table());
let tool_recipes = game_data.get("tool_recipes").and_then(|v| v.as_table());
// Get all available items to validate recipes
let items = game_data
.get("items")
.and_then(|v| v.as_table())
.expect("Missing [items] table in game data");
let available_items: std::collections::HashSet<String> = items.keys().cloned().collect();
// Read tool names from tools.toml
let tools_toml_path = Path::new("assets/data/tools.toml");
let tools_content = fs::read_to_string(tools_toml_path).expect("Failed to read tools.toml");
let tools_data: toml::Table =
toml::from_str(&tools_content).expect("Failed to parse tools.toml");
let mut tool_names = Vec::new();
// Extract pickaxe names
if let Some(pick_table) = tools_data.get("pick").and_then(|v| v.as_table()) {
for (level, data) in pick_table.iter() {
if let Some(name) = data
.as_table()
.and_then(|t| t.get("name"))
.and_then(|n| n.as_str())
{
tool_names.push(format!(" \"{}\" => \"{}\",", level, name));
}
}
}
// Extract dash names
if let Some(dash_table) = tools_data.get("dash").and_then(|v| v.as_table()) {
for (level, data) in dash_table.iter() {
if let Some(name) = data
.as_table()
.and_then(|t| t.get("name"))
.and_then(|n| n.as_str())
{
tool_names.push(format!(" \"{}\" => \"{}\",", level, name));
}
}
}
// Extract glider names
if let Some(glider_table) = tools_data.get("glider").and_then(|v| v.as_table()) {
for (level, data) in glider_table.iter() {
if let Some(name) = data
.as_table()
.and_then(|t| t.get("name"))
.and_then(|n| n.as_str())
{
tool_names.push(format!(" \"{}\" => \"{}\",", level, name));
}
}
}
let mut recipe_definitions = Vec::new();
let mut skipped_recipes = Vec::new();
// Helper function to classify input/output type
let classify_io = |name: &str| -> String {
let normalized = name.replace(" ", "_");
// Check if it's a regular item
if available_items.contains(&normalized) {
return String::from("item");
}
// Check if it's a tool by name pattern
if normalized.contains("pickaxe") {
return String::from("tool_pickaxe");
}
if normalized.contains("amulet") {
return String::from("tool_dash");
}
if normalized.contains("glider") {
return String::from("tool_glider");
}
if normalized == "tidalcave_clock" {
return String::from("tool_tideclock");
}
String::from("unknown")
};
// Process regular recipes
if let Some(recipes) = recipes {
for (key, value) in recipes.iter() {
process_recipe(
key,
value,
&available_items,
&classify_io,
&mut recipe_definitions,
&mut skipped_recipes,
);
}
}
// Process tool recipes
if let Some(tool_recipes) = tool_recipes {
for (key, value) in tool_recipes.iter() {
process_recipe(
key,
value,
&available_items,
&classify_io,
&mut recipe_definitions,
&mut skipped_recipes,
);
}
}
if !skipped_recipes.is_empty() {
println!(
"cargo:warning=Skipped {} recipes due to missing items:",
skipped_recipes.len()
);
for skipped in &skipped_recipes {
println!("cargo:warning= - {}", skipped);
}
}
let generated_code = format!(
r#"// Generated recipe definitions
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecipeType {{
Workbench,
Furnace,
Anvil,
Always
}}
#[derive(Debug, Clone, Copy)]
pub enum RecipeIOType {{
Item {{ item_type: ItemType, amount: u32 }},
ToolPickaxe {{ level: &'static str }},
ToolDash {{ level: &'static str }},
ToolGlider {{ level: &'static str }},
ToolTideClock,
}}
impl RecipeIOType {{
/// Returns the display name for this recipe input/output
pub fn name(&self) -> &'static str {{
match self {{
RecipeIOType::Item {{ item_type, .. }} => item_type.name(),
RecipeIOType::ToolPickaxe {{ level }} | RecipeIOType::ToolDash {{ level }} | RecipeIOType::ToolGlider {{ level }} => {{
match *level {{
{}
_ => level,
}}
}}
RecipeIOType::ToolTideClock => "Tidalcave Clock",
}}
}}
/// Returns the amount for this recipe input/output
pub fn amount(&self) -> u32 {{
match self {{
RecipeIOType::Item {{ amount, .. }} => *amount,
RecipeIOType::ToolPickaxe {{ .. }} => 1,
RecipeIOType::ToolDash {{ .. }} => 1,
RecipeIOType::ToolGlider {{ .. }} => 1,
RecipeIOType::ToolTideClock => 1,
}}
}}
/// Returns the texture for this recipe input/output
pub fn get_texture<'a>(&self, textures: &'a crate::TextureManager) -> &'a raylib::prelude::Texture2D {{
match self {{
RecipeIOType::Item {{ item_type, .. }} => item_type.get_texture(textures),
RecipeIOType::ToolPickaxe {{ level }} => {{
crate::tools::ToolPickaxe::texture_for_level(level, textures)
}}
RecipeIOType::ToolDash {{ level }} => {{
crate::tools::ToolDash::texture_for_level(level, textures)