wave_function_collapse/wave_function/collapsable_wave_function/
collapsable_wave_function.rs

1use std::fmt::Display;
2use std::{collections::HashMap, marker::PhantomData};
3use std::rc::Rc;
4use std::cell::RefCell;
5use bitvec::vec::BitVec;
6use fastrand::Rng;
7use serde::{Serialize, Deserialize};
8use std::hash::Hash;
9use crate::wave_function::indexed_view::IndexedView;
10
11/// This trait defines the relationship between collapsable nodes and a collapsed state.
12pub trait CollapsableWaveFunction<'a, TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> {
13    fn new(collapsable_nodes: Vec<Rc<RefCell<CollapsableNode<'a, TNodeState>>>>, collapsable_node_per_id: HashMap<&'a str, Rc<RefCell<CollapsableNode<'a, TNodeState>>>>, random_instance: Rc<RefCell<fastrand::Rng>>) -> Self where Self: Sized;
14    fn collapse_into_steps(&'a mut self) -> Result<Vec<CollapsedNodeState<TNodeState>>, String>;
15    fn collapse(&'a mut self) -> Result<CollapsedWaveFunction<TNodeState>, String>;
16}
17
18#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq, Hash)]
19pub struct CollapsedNodeState<TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> {
20    pub node_id: String,
21    pub node_state_id: Option<TNodeState>
22}
23
24#[derive(Serialize)]
25pub struct CollapsedWaveFunction<TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> {
26    pub node_state_per_node_id: HashMap<String, TNodeState>
27}
28
29#[derive(Clone, Eq, PartialEq, Debug)]
30pub struct UncollapsedWaveFunction<TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> {
31    pub node_state_per_node: HashMap<String, Option<TNodeState>>
32}
33
34impl<TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> Hash for UncollapsedWaveFunction<TNodeState> {
35    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
36        for property in self.node_state_per_node.iter() {
37            property.hash(state);
38        }
39    }
40}
41
42/// This struct represents a stateful node in a collapsable wave function which references a base node from the wave function.
43#[derive(Debug)]
44pub struct CollapsableNode<'a, TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> {
45    // the node id that this collapsable node refers to
46    pub id: &'a str,
47    // this nodes list of neighbor node ids
48    pub neighbor_node_ids: Vec<&'a str>,
49    // the full list of possible node states, masked by internal references to neighbor masks
50    pub node_state_indexed_view: IndexedView<&'a TNodeState>,
51    // the mapped view that this node's neighbors will have a reference to and pull their masks from
52    pub mask_per_neighbor_per_state: HashMap<&'a TNodeState, HashMap<&'a str, BitVec>>,
53    // the index of traversed nodes based on the sorted vector of nodes as they are chosen for state determination
54    pub current_chosen_from_sort_index: Option<usize>,
55    // the neighbors that are pointing to this collapsable node
56    pub parent_neighbor_node_ids: Vec<&'a str>,
57    // allowing for Node<TNodeState> to be an argument of CollapsableNode functions
58    node_state_type: PhantomData<TNodeState>
59}
60
61impl<'a, TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> CollapsableNode<'a, TNodeState> {
62    pub fn new(id: &'a str, node_state_collection_ids_per_neighbor_node_id: &'a HashMap<String, Vec<String>>, mask_per_neighbor_per_state: HashMap<&'a TNodeState, HashMap<&'a str, BitVec>>, node_state_indexed_view: IndexedView<&'a TNodeState>) -> Self {
63        // get the neighbors for this node
64        let mut neighbor_node_ids: Vec<&str> = Vec::new();
65
66        for neighbor_node_id_string in node_state_collection_ids_per_neighbor_node_id.keys() {
67            let neighbor_node_id: &str = neighbor_node_id_string;
68            neighbor_node_ids.push(neighbor_node_id);
69        }
70        neighbor_node_ids.sort();
71
72        CollapsableNode {
73            id,
74            neighbor_node_ids,
75            node_state_indexed_view,
76            mask_per_neighbor_per_state,
77            current_chosen_from_sort_index: None,
78            parent_neighbor_node_ids: Vec::new(),
79            node_state_type: PhantomData
80        }
81    }
82    pub fn randomize(&mut self, random_instance: &mut Rng) {
83        self.node_state_indexed_view.shuffle(random_instance);
84    }
85    pub fn is_fully_restricted(&mut self) -> bool {
86        self.node_state_indexed_view.is_fully_restricted() || self.node_state_indexed_view.is_current_state_restricted()
87    }
88    pub fn add_mask(&mut self, mask: &BitVec) {
89        self.node_state_indexed_view.add_mask(mask);
90    }
91    pub fn subtract_mask(&mut self, mask: &BitVec) {
92        self.node_state_indexed_view.subtract_mask(mask);
93    }
94    pub fn forward_mask(&mut self, mask: &BitVec) {
95        self.node_state_indexed_view.forward_mask(mask);
96    }
97    pub fn reverse_mask(&mut self) {
98        self.node_state_indexed_view.reverse_mask();
99    }
100    pub fn is_mask_restrictive_to_current_state(&self, mask: &BitVec) -> bool {
101        let is_restrictive = self.node_state_indexed_view.is_mask_restrictive_to_current_state(mask);
102        if is_restrictive {
103            debug!("mask is restrictive");
104        }
105        else {
106            debug!("mask is not restrictive");
107        }
108        is_restrictive
109    }
110}
111
112impl<'a, TNodeState: Eq + Hash + Clone + std::fmt::Debug + Ord> Display for CollapsableNode<'a, TNodeState> {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        write!(f, "{}", self.id)
115    }
116}