Wfc

Struct Wfc 

Source
pub struct Wfc { /* private fields */ }

Implementations§

Source§

impl Wfc

Source

pub fn new(config: WfcConfig) -> Self

Examples found in repository?
examples/enhanced_wfc.rs (lines 29-33)
10fn main() {
11    println!("=== Enhanced Wave Function Collapse Demo ===\n");
12
13    // Step 1: Generate example map for pattern learning
14    println!("1. Generating Example Map for Pattern Learning:");
15    let mut example_grid = Grid::new(20, 15);
16    let bsp = Bsp::default();
17    bsp.generate(&mut example_grid, 54321);
18
19    print_grid(&example_grid, "Example Map");
20
21    // Step 2: Extract patterns from example
22    println!("\n2. Extracting Patterns from Example:");
23    let patterns = WfcPatternExtractor::extract_patterns(&example_grid, 3);
24    println!("   Extracted {} unique patterns", patterns.len());
25
26    // Step 3: Generate with learned patterns (no backtracking)
27    println!("\n3. WFC Generation without Backtracking:");
28    let mut grid1 = Grid::new(25, 20);
29    let wfc_no_backtrack = Wfc::new(WfcConfig {
30        floor_weight: 0.4,
31        pattern_size: 3,
32        enable_backtracking: false,
33    });
34    wfc_no_backtrack.generate_with_patterns(&mut grid1, patterns.clone(), 12345);
35    print_grid(&grid1, "Without Backtracking");
36
37    // Step 4: Generate with backtracking enabled
38    println!("\n4. WFC Generation with Backtracking:");
39    let mut grid2 = Grid::new(25, 20);
40    let wfc_backtrack = Wfc::new(WfcConfig {
41        floor_weight: 0.4,
42        pattern_size: 3,
43        enable_backtracking: true,
44    });
45    wfc_backtrack.generate_with_patterns(&mut grid2, patterns.clone(), 12345);
46    print_grid(&grid2, "With Backtracking");
47
48    // Step 5: Compare results
49    println!("\n5. Comparison:");
50    let floors1 = grid1.count(|t| t.is_floor());
51    let floors2 = grid2.count(|t| t.is_floor());
52
53    println!(
54        "   Without backtracking: {} floors ({:.1}%)",
55        floors1,
56        100.0 * floors1 as f32 / (grid1.width() * grid1.height()) as f32
57    );
58    println!(
59        "   With backtracking: {} floors ({:.1}%)",
60        floors2,
61        100.0 * floors2 as f32 / (grid2.width() * grid2.height()) as f32
62    );
63
64    // Step 6: Different pattern sizes
65    println!("\n6. Pattern Size Comparison:");
66    for size in [2, 3, 4] {
67        let patterns = WfcPatternExtractor::extract_patterns(&example_grid, size);
68        let mut grid = Grid::new(15, 12);
69        let wfc = Wfc::new(WfcConfig {
70            floor_weight: 0.4,
71            pattern_size: size,
72            enable_backtracking: true,
73        });
74        wfc.generate_with_patterns(&mut grid, patterns.clone(), 98765);
75
76        let floors = grid.count(|t| t.is_floor());
77        println!(
78            "   Pattern size {}: {} patterns, {} floors",
79            size,
80            patterns.len(),
81            floors
82        );
83    }
84
85    println!("\n✅ Enhanced WFC demo complete!");
86    println!("   - Pattern learning extracts reusable structures");
87    println!("   - Backtracking improves generation success rate");
88    println!("   - Constraint propagation ensures valid outputs");
89}
More examples
Hide additional examples
examples/phase4_workflow.rs (lines 42-46)
14fn main() {
15    println!("=== Phase 4 Complete Workflow Demo ===\n");
16
17    // Step 1: Generate base layout with BSP
18    println!("1. Generating Base Layout:");
19    let mut base_grid = Grid::new(35, 25);
20    let bsp = Bsp::default();
21    bsp.generate(&mut base_grid, 12345);
22
23    let base_floors = base_grid.count(|t| t.is_floor());
24    println!(
25        "   Generated {}x{} base layout with {} floors",
26        base_grid.width(),
27        base_grid.height(),
28        base_floors
29    );
30
31    // Step 2: Learn patterns from base layout
32    println!("\n2. Learning Patterns from Base Layout:");
33    let learned_patterns = WfcPatternExtractor::extract_patterns(&base_grid, 3);
34    println!(
35        "   Extracted {} unique 3x3 patterns",
36        learned_patterns.len()
37    );
38
39    // Step 3: Generate enhanced areas with WFC
40    println!("\n3. Generating Enhanced Areas with Learned Patterns:");
41    let mut wfc_grid = Grid::new(20, 15);
42    let wfc = Wfc::new(WfcConfig {
43        floor_weight: 0.45,
44        pattern_size: 3,
45        enable_backtracking: true,
46    });
47    wfc.generate_with_patterns(&mut wfc_grid, learned_patterns.clone(), 54321);
48
49    let wfc_floors = wfc_grid.count(|t| t.is_floor());
50    println!(
51        "   WFC generated {} floors with learned patterns",
52        wfc_floors
53    );
54
55    // Step 4: Find room centers for connectivity analysis
56    println!("\n4. Analyzing Room Connectivity:");
57    let room_centers = find_room_centers(&base_grid);
58    println!("   Identified {} room centers", room_centers.len());
59
60    // Step 5: Create optimal connections with Delaunay + MST
61    println!("\n5. Creating Optimal Room Connections:");
62    if room_centers.len() >= 3 {
63        let triangulation = DelaunayTriangulation::new(room_centers.clone());
64        let mst_edges = triangulation.minimum_spanning_tree();
65
66        println!("   Delaunay triangulation:");
67        println!("     Triangles: {}", triangulation.triangles.len());
68        println!("     All edges: {}", triangulation.edges.len());
69
70        println!("   Minimum spanning tree:");
71        println!("     Optimal edges: {}", mst_edges.len());
72
73        let total_length: f32 = mst_edges
74            .iter()
75            .map(|edge| edge.length(&triangulation.points))
76            .sum();
77        println!("     Total corridor length: {:.1}", total_length);
78
79        // Graph analysis
80        let graph = Graph::new(triangulation.points.clone(), mst_edges);
81        let analysis = GraphAnalysis::analyze(&graph);
82
83        println!("   Connectivity analysis:");
84        println!("     Connected: {}", analysis.is_connected);
85        println!("     Diameter: {:.1}", analysis.diameter);
86        println!("     Clustering: {:.3}", analysis.average_clustering);
87    } else {
88        println!("   Not enough rooms for connectivity analysis");
89    }
90
91    // Step 6: Create specialized prefab library
92    println!("\n6. Creating Specialized Prefab Library:");
93    let library = create_specialized_library();
94
95    println!(
96        "   Created library with {} prefabs:",
97        library.get_prefabs().len()
98    );
99    for prefab in library.get_prefabs() {
100        println!(
101            "     - {} (weight: {:.1}, tags: {:?})",
102            prefab.name, prefab.weight, prefab.tags
103        );
104    }
105
106    // Step 7: Place special features with advanced prefabs
107    println!("\n7. Placing Special Features:");
108    let mut feature_grid = Grid::new(30, 20);
109
110    // Place boss rooms (rare, large)
111    let boss_config = PrefabConfig {
112        max_prefabs: 1,
113        min_spacing: 8,
114        allow_rotation: false,
115        allow_mirroring: false,
116        weighted_selection: true,
117    };
118
119    let boss_placer = PrefabPlacer::new(boss_config, library.clone());
120    boss_placer.generate(&mut feature_grid, 98765);
121
122    // Place treasure rooms (medium rarity)
123    let treasure_config = PrefabConfig {
124        max_prefabs: 2,
125        min_spacing: 5,
126        allow_rotation: true,
127        allow_mirroring: true,
128        weighted_selection: true,
129    };
130
131    let treasure_placer = PrefabPlacer::new(treasure_config, library.clone());
132    treasure_placer.generate(&mut feature_grid, 13579);
133
134    let feature_floors = feature_grid.count(|t| t.is_floor());
135    println!("   Placed special features: {} floor tiles", feature_floors);
136
137    // Step 8: Performance and quality metrics
138    println!("\n8. Performance and Quality Metrics:");
139
140    // WFC performance
141    let start = std::time::Instant::now();
142    let mut perf_grid = Grid::new(25, 20);
143    wfc.generate_with_patterns(&mut perf_grid, learned_patterns.clone(), 24680);
144    let wfc_time = start.elapsed();
145
146    // Prefab performance
147    let start = std::time::Instant::now();
148    let placer = PrefabPlacer::new(PrefabConfig::default(), library.clone());
149    let mut prefab_grid = Grid::new(25, 20);
150    placer.generate(&mut prefab_grid, 24680);
151    let prefab_time = start.elapsed();
152
153    // Delaunay performance
154    let start = std::time::Instant::now();
155    let _ = DelaunayTriangulation::new(room_centers.clone());
156    let delaunay_time = start.elapsed();
157
158    println!("   Performance metrics:");
159    println!("     WFC generation: {:?}", wfc_time);
160    println!("     Prefab placement: {:?}", prefab_time);
161    println!("     Delaunay triangulation: {:?}", delaunay_time);
162
163    // Step 9: Quality comparison
164    println!("\n9. Quality Comparison:");
165
166    // Basic generation
167    let mut basic_grid = Grid::new(25, 20);
168    bsp.generate(&mut basic_grid, 11111);
169    let basic_floors = basic_grid.count(|t| t.is_floor());
170
171    // Enhanced generation (WFC + prefabs)
172    let enhanced_floors = perf_grid.count(|t| t.is_floor()) + prefab_grid.count(|t| t.is_floor());
173
174    println!("   Floor tile comparison:");
175    println!(
176        "     Basic BSP: {} floors ({:.1}%)",
177        basic_floors,
178        100.0 * basic_floors as f32 / (25 * 20) as f32
179    );
180    println!(
181        "     Enhanced (WFC + Prefabs): {} floors ({:.1}%)",
182        enhanced_floors,
183        100.0 * enhanced_floors as f32 / (50 * 20) as f32
184    );
185
186    // Step 10: Save configuration for reuse
187    println!("\n10. Saving Configuration:");
188    match library.save_to_json("phase4_library.json") {
189        Ok(()) => println!("   ✅ Saved prefab library to phase4_library.json"),
190        Err(e) => println!("   ❌ Failed to save library: {}", e),
191    }
192
193    println!("\n✅ Phase 4 complete workflow finished!");
194    println!("   Workflow summary:");
195    println!("   1. Generated base layout with BSP algorithm");
196    println!(
197        "   2. Learned {} patterns for WFC enhancement",
198        learned_patterns.len()
199    );
200    println!(
201        "   3. Analyzed {} room connections with Delaunay triangulation",
202        room_centers.len()
203    );
204    println!("   4. Placed specialized features with weighted prefab selection");
205    println!("   5. Achieved optimal room connectivity with MST");
206    println!("   6. Demonstrated pattern learning and constraint propagation");
207    println!("   \n   Phase 4 features enable:");
208    println!("   - Intelligent pattern-based generation");
209    println!("   - Mathematically optimal room connections");
210    println!("   - Flexible, reusable prefab systems");
211    println!("   - Advanced graph analysis for level design");
212}
Source

pub fn generate_with_patterns( &self, grid: &mut Grid<Tile>, patterns: Vec<Pattern>, seed: u64, )

Examples found in repository?
examples/enhanced_wfc.rs (line 34)
10fn main() {
11    println!("=== Enhanced Wave Function Collapse Demo ===\n");
12
13    // Step 1: Generate example map for pattern learning
14    println!("1. Generating Example Map for Pattern Learning:");
15    let mut example_grid = Grid::new(20, 15);
16    let bsp = Bsp::default();
17    bsp.generate(&mut example_grid, 54321);
18
19    print_grid(&example_grid, "Example Map");
20
21    // Step 2: Extract patterns from example
22    println!("\n2. Extracting Patterns from Example:");
23    let patterns = WfcPatternExtractor::extract_patterns(&example_grid, 3);
24    println!("   Extracted {} unique patterns", patterns.len());
25
26    // Step 3: Generate with learned patterns (no backtracking)
27    println!("\n3. WFC Generation without Backtracking:");
28    let mut grid1 = Grid::new(25, 20);
29    let wfc_no_backtrack = Wfc::new(WfcConfig {
30        floor_weight: 0.4,
31        pattern_size: 3,
32        enable_backtracking: false,
33    });
34    wfc_no_backtrack.generate_with_patterns(&mut grid1, patterns.clone(), 12345);
35    print_grid(&grid1, "Without Backtracking");
36
37    // Step 4: Generate with backtracking enabled
38    println!("\n4. WFC Generation with Backtracking:");
39    let mut grid2 = Grid::new(25, 20);
40    let wfc_backtrack = Wfc::new(WfcConfig {
41        floor_weight: 0.4,
42        pattern_size: 3,
43        enable_backtracking: true,
44    });
45    wfc_backtrack.generate_with_patterns(&mut grid2, patterns.clone(), 12345);
46    print_grid(&grid2, "With Backtracking");
47
48    // Step 5: Compare results
49    println!("\n5. Comparison:");
50    let floors1 = grid1.count(|t| t.is_floor());
51    let floors2 = grid2.count(|t| t.is_floor());
52
53    println!(
54        "   Without backtracking: {} floors ({:.1}%)",
55        floors1,
56        100.0 * floors1 as f32 / (grid1.width() * grid1.height()) as f32
57    );
58    println!(
59        "   With backtracking: {} floors ({:.1}%)",
60        floors2,
61        100.0 * floors2 as f32 / (grid2.width() * grid2.height()) as f32
62    );
63
64    // Step 6: Different pattern sizes
65    println!("\n6. Pattern Size Comparison:");
66    for size in [2, 3, 4] {
67        let patterns = WfcPatternExtractor::extract_patterns(&example_grid, size);
68        let mut grid = Grid::new(15, 12);
69        let wfc = Wfc::new(WfcConfig {
70            floor_weight: 0.4,
71            pattern_size: size,
72            enable_backtracking: true,
73        });
74        wfc.generate_with_patterns(&mut grid, patterns.clone(), 98765);
75
76        let floors = grid.count(|t| t.is_floor());
77        println!(
78            "   Pattern size {}: {} patterns, {} floors",
79            size,
80            patterns.len(),
81            floors
82        );
83    }
84
85    println!("\n✅ Enhanced WFC demo complete!");
86    println!("   - Pattern learning extracts reusable structures");
87    println!("   - Backtracking improves generation success rate");
88    println!("   - Constraint propagation ensures valid outputs");
89}
More examples
Hide additional examples
examples/phase4_workflow.rs (line 47)
14fn main() {
15    println!("=== Phase 4 Complete Workflow Demo ===\n");
16
17    // Step 1: Generate base layout with BSP
18    println!("1. Generating Base Layout:");
19    let mut base_grid = Grid::new(35, 25);
20    let bsp = Bsp::default();
21    bsp.generate(&mut base_grid, 12345);
22
23    let base_floors = base_grid.count(|t| t.is_floor());
24    println!(
25        "   Generated {}x{} base layout with {} floors",
26        base_grid.width(),
27        base_grid.height(),
28        base_floors
29    );
30
31    // Step 2: Learn patterns from base layout
32    println!("\n2. Learning Patterns from Base Layout:");
33    let learned_patterns = WfcPatternExtractor::extract_patterns(&base_grid, 3);
34    println!(
35        "   Extracted {} unique 3x3 patterns",
36        learned_patterns.len()
37    );
38
39    // Step 3: Generate enhanced areas with WFC
40    println!("\n3. Generating Enhanced Areas with Learned Patterns:");
41    let mut wfc_grid = Grid::new(20, 15);
42    let wfc = Wfc::new(WfcConfig {
43        floor_weight: 0.45,
44        pattern_size: 3,
45        enable_backtracking: true,
46    });
47    wfc.generate_with_patterns(&mut wfc_grid, learned_patterns.clone(), 54321);
48
49    let wfc_floors = wfc_grid.count(|t| t.is_floor());
50    println!(
51        "   WFC generated {} floors with learned patterns",
52        wfc_floors
53    );
54
55    // Step 4: Find room centers for connectivity analysis
56    println!("\n4. Analyzing Room Connectivity:");
57    let room_centers = find_room_centers(&base_grid);
58    println!("   Identified {} room centers", room_centers.len());
59
60    // Step 5: Create optimal connections with Delaunay + MST
61    println!("\n5. Creating Optimal Room Connections:");
62    if room_centers.len() >= 3 {
63        let triangulation = DelaunayTriangulation::new(room_centers.clone());
64        let mst_edges = triangulation.minimum_spanning_tree();
65
66        println!("   Delaunay triangulation:");
67        println!("     Triangles: {}", triangulation.triangles.len());
68        println!("     All edges: {}", triangulation.edges.len());
69
70        println!("   Minimum spanning tree:");
71        println!("     Optimal edges: {}", mst_edges.len());
72
73        let total_length: f32 = mst_edges
74            .iter()
75            .map(|edge| edge.length(&triangulation.points))
76            .sum();
77        println!("     Total corridor length: {:.1}", total_length);
78
79        // Graph analysis
80        let graph = Graph::new(triangulation.points.clone(), mst_edges);
81        let analysis = GraphAnalysis::analyze(&graph);
82
83        println!("   Connectivity analysis:");
84        println!("     Connected: {}", analysis.is_connected);
85        println!("     Diameter: {:.1}", analysis.diameter);
86        println!("     Clustering: {:.3}", analysis.average_clustering);
87    } else {
88        println!("   Not enough rooms for connectivity analysis");
89    }
90
91    // Step 6: Create specialized prefab library
92    println!("\n6. Creating Specialized Prefab Library:");
93    let library = create_specialized_library();
94
95    println!(
96        "   Created library with {} prefabs:",
97        library.get_prefabs().len()
98    );
99    for prefab in library.get_prefabs() {
100        println!(
101            "     - {} (weight: {:.1}, tags: {:?})",
102            prefab.name, prefab.weight, prefab.tags
103        );
104    }
105
106    // Step 7: Place special features with advanced prefabs
107    println!("\n7. Placing Special Features:");
108    let mut feature_grid = Grid::new(30, 20);
109
110    // Place boss rooms (rare, large)
111    let boss_config = PrefabConfig {
112        max_prefabs: 1,
113        min_spacing: 8,
114        allow_rotation: false,
115        allow_mirroring: false,
116        weighted_selection: true,
117    };
118
119    let boss_placer = PrefabPlacer::new(boss_config, library.clone());
120    boss_placer.generate(&mut feature_grid, 98765);
121
122    // Place treasure rooms (medium rarity)
123    let treasure_config = PrefabConfig {
124        max_prefabs: 2,
125        min_spacing: 5,
126        allow_rotation: true,
127        allow_mirroring: true,
128        weighted_selection: true,
129    };
130
131    let treasure_placer = PrefabPlacer::new(treasure_config, library.clone());
132    treasure_placer.generate(&mut feature_grid, 13579);
133
134    let feature_floors = feature_grid.count(|t| t.is_floor());
135    println!("   Placed special features: {} floor tiles", feature_floors);
136
137    // Step 8: Performance and quality metrics
138    println!("\n8. Performance and Quality Metrics:");
139
140    // WFC performance
141    let start = std::time::Instant::now();
142    let mut perf_grid = Grid::new(25, 20);
143    wfc.generate_with_patterns(&mut perf_grid, learned_patterns.clone(), 24680);
144    let wfc_time = start.elapsed();
145
146    // Prefab performance
147    let start = std::time::Instant::now();
148    let placer = PrefabPlacer::new(PrefabConfig::default(), library.clone());
149    let mut prefab_grid = Grid::new(25, 20);
150    placer.generate(&mut prefab_grid, 24680);
151    let prefab_time = start.elapsed();
152
153    // Delaunay performance
154    let start = std::time::Instant::now();
155    let _ = DelaunayTriangulation::new(room_centers.clone());
156    let delaunay_time = start.elapsed();
157
158    println!("   Performance metrics:");
159    println!("     WFC generation: {:?}", wfc_time);
160    println!("     Prefab placement: {:?}", prefab_time);
161    println!("     Delaunay triangulation: {:?}", delaunay_time);
162
163    // Step 9: Quality comparison
164    println!("\n9. Quality Comparison:");
165
166    // Basic generation
167    let mut basic_grid = Grid::new(25, 20);
168    bsp.generate(&mut basic_grid, 11111);
169    let basic_floors = basic_grid.count(|t| t.is_floor());
170
171    // Enhanced generation (WFC + prefabs)
172    let enhanced_floors = perf_grid.count(|t| t.is_floor()) + prefab_grid.count(|t| t.is_floor());
173
174    println!("   Floor tile comparison:");
175    println!(
176        "     Basic BSP: {} floors ({:.1}%)",
177        basic_floors,
178        100.0 * basic_floors as f32 / (25 * 20) as f32
179    );
180    println!(
181        "     Enhanced (WFC + Prefabs): {} floors ({:.1}%)",
182        enhanced_floors,
183        100.0 * enhanced_floors as f32 / (50 * 20) as f32
184    );
185
186    // Step 10: Save configuration for reuse
187    println!("\n10. Saving Configuration:");
188    match library.save_to_json("phase4_library.json") {
189        Ok(()) => println!("   ✅ Saved prefab library to phase4_library.json"),
190        Err(e) => println!("   ❌ Failed to save library: {}", e),
191    }
192
193    println!("\n✅ Phase 4 complete workflow finished!");
194    println!("   Workflow summary:");
195    println!("   1. Generated base layout with BSP algorithm");
196    println!(
197        "   2. Learned {} patterns for WFC enhancement",
198        learned_patterns.len()
199    );
200    println!(
201        "   3. Analyzed {} room connections with Delaunay triangulation",
202        room_centers.len()
203    );
204    println!("   4. Placed specialized features with weighted prefab selection");
205    println!("   5. Achieved optimal room connectivity with MST");
206    println!("   6. Demonstrated pattern learning and constraint propagation");
207    println!("   \n   Phase 4 features enable:");
208    println!("   - Intelligent pattern-based generation");
209    println!("   - Mathematically optimal room connections");
210    println!("   - Flexible, reusable prefab systems");
211    println!("   - Advanced graph analysis for level design");
212}

Trait Implementations§

Source§

impl Algorithm for Wfc

Source§

fn generate(&self, grid: &mut Grid<Tile>, seed: u64)

Generate content into the grid using the given seed
Source§

fn name(&self) -> &'static str

Algorithm name for identification
Source§

impl Default for Wfc

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for Wfc

§

impl RefUnwindSafe for Wfc

§

impl Send for Wfc

§

impl Sync for Wfc

§

impl Unpin for Wfc

§

impl UnwindSafe for Wfc

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V