๐Ÿ“ฆ tychedelia / sepiascraped

๐Ÿ“„ mod.rs ยท 211 lines
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
211use bevy::ecs::system::SystemParam;
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::ops::DerefMut;

use bevy::prelude::*;
use bevy::utils::AHasher;

use crate::index::{CompositeIndex2, CompositeIndex2Plugin};
use crate::op::{OpCategory, OpRef};
use crate::script::update;
use crate::Sets;

pub struct ParamPlugin;

impl Plugin for ParamPlugin {
    fn build(&self, app: &mut App) {
        app
            .init_resource::<ParamsHash>()
            .add_systems(Update, validate.after(update).in_set(Sets::Params))
            .add_plugins(CompositeIndex2Plugin::<OpRef, ParamName>::new());
    }
}

#[derive(Bundle, Default, Clone)]
pub struct ParamBundle {
    pub name: ParamName,
    pub value: ParamValue,
    pub order: ParamOrder,
    pub page: ParamPage,
}

#[derive(Component, Clone, Default, Debug)]
pub struct ParamPage(pub String);
#[derive(Component, Clone, Default, Debug, Eq, Ord, PartialOrd, PartialEq)]
pub struct ParamOrder(pub u32);
#[derive(Component, Clone, Default, Debug)]
pub struct Param;
#[derive(
    Component, Deref, DerefMut, Default, Clone, PartialEq, Eq, Hash, Debug, Ord, PartialOrd,
)]
pub struct ParamName(pub String);

trait ParamType: Default {}

#[derive(Component, PartialEq, Clone, Debug, Default)]
pub enum ParamValue {
    #[default]
    None,
    F32(f32),
    U32(u32),
    UVec2(UVec2),
    Vec2(Vec2),
    Vec3(Vec3),
    Quat(Quat),
    Color(Vec4),
    Bool(bool),
    TextureOp(Option<Entity>),
    MeshOp(Option<Entity>),
}

impl Hash for ParamValue {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            ParamValue::None => 0.hash(state),
            ParamValue::F32(v) => v.to_bits().hash(state),
            ParamValue::U32(v) => v.hash(state),
            ParamValue::UVec2(v) => v.hash(state),
            ParamValue::Vec2(v) => {
                v.x.to_bits().hash(state);
                v.y.to_bits().hash(state);
            },
            ParamValue::Vec3(v) => {
                v.x.to_bits().hash(state);
                v.y.to_bits().hash(state);
                v.z.to_bits().hash(state);
            },
            ParamValue::Quat(v) => {
                v.x.to_bits().hash(state);
                v.y.to_bits().hash(state);
                v.z.to_bits().hash(state);
                v.w.to_bits().hash(state);
            },
            ParamValue::Color(v) => {
                v.x.to_bits().hash(state);
                v.y.to_bits().hash(state);
                v.z.to_bits().hash(state);
                v.w.to_bits().hash(state);
            },
            ParamValue::Bool(v) => v.hash(state),
            ParamValue::TextureOp(v) => v.hash(state),
            ParamValue::MeshOp(v) => v.hash(state),
        }
    }
}

#[derive(Resource, Default, Debug)]
pub struct ParamsHash {
    pub hashes: BTreeMap<Entity, u64>,
}

#[derive(Component, Deref, DerefMut, Default, Debug)]
pub struct ParamHash(pub u64);

#[derive(Component, Default, Debug)]
pub struct ScriptedParam;
#[derive(Component, Default, Debug)]
pub struct ScriptedParamError(pub String);

fn validate(
    mut commands: Commands,
    mut params_q: Query<(Entity, &mut ParamValue), Changed<ParamValue>>,
    category_q: Query<&OpCategory>,
) {
    for (entity, mut param_value) in params_q.iter_mut() {
        match param_value.deref_mut() {
            ParamValue::TextureOp(Some(e)) => {
                let category = category_q.get(*e).unwrap();
                if !category.is_texture() {
                    commands
                        .entity(entity)
                        .insert(ScriptedParamError("Invalid texture".to_string()));
                    *param_value = ParamValue::TextureOp(None);
                }
            }
            ParamValue::MeshOp(Some(e)) => {
                let category = category_q.get(*e).unwrap();
                if !category.is_mesh() {
                    commands
                        .entity(entity)
                        .insert(ScriptedParamError("Invalid mesh".to_string()));
                    *param_value = ParamValue::MeshOp(None);
                }
            }
            _ => {}
        }
    }
}

#[derive(SystemParam)]
pub struct Params<'w, 's> {
    parent_q: Query<'w, 's, &'static Children>,
    params_q: Query<'w, 's, &'static mut ParamValue>,
    param_idx: Res<'w, CompositeIndex2<OpRef, ParamName>>,
}

impl<'w, 's> Params<'w, 's> {
    // Get the hash of all the parameters for an entity
    pub fn hash(&self, entity: Entity) -> u64 {
        self.parent_q.get(entity)
            .iter()
            .flat_map(|c| c.iter().map(|e| self.params_q.get(*e)))
            .filter_map(|p| p.ok())
            .fold(AHasher::default(), |mut h, p| {
                p.hash(&mut h);
                h
            })
            .finish()
    }

    pub fn get_all(&self, entity: Entity) -> Vec<&ParamValue> {
        self.parent_q.get(entity)
            .iter()
            .flat_map(|c| c.iter().map(|e| self.params_q.get(*e)))
            .filter_map(|p| p.ok())
            .collect()
    }

    pub fn get(&self, entity: Entity, name: impl Into<String>) -> Option<&ParamValue> {
        self.param_idx
            .get(&(OpRef(entity), ParamName(name.into())))
            .map(|e| self.params_q.get(*e).unwrap())
    }

    pub fn get_mut(&mut self, entity: Entity, name: impl Into<String>) -> Option<Mut<ParamValue>> {
        self.param_idx
            .get(&(OpRef(entity), ParamName(name.into())))
            .map(|e| self.params_q.get_mut(*e).unwrap())
    }
}

pub trait IntoParams {
    fn as_params(&self) -> Vec<ParamBundle>;
}

/// IntoParams for Transform
impl IntoParams for Transform {
    fn as_params(&self) -> Vec<ParamBundle> {
        vec![
            ParamBundle {
                name: ParamName("Translation".to_string()),
                value: ParamValue::Vec3(self.translation),
                order: ParamOrder(0),
                ..default()
            },
            ParamBundle {
                name: ParamName("Rotation".to_string()),
                value: ParamValue::Quat(self.rotation),
                order: ParamOrder(1),
                ..default()
            },
            ParamBundle {
                name: ParamName("Scale".to_string()),
                value: ParamValue::Vec3(self.scale),
                order: ParamOrder(2),
                ..default()
            },
        ]
    }
}