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
use std::collections::{btree_map, BTreeMap};
use derive_new::new;
use legion::world::SubWorld;
use legion::Entity;
use smallvec::SmallVec;
use typed_builder::TypedBuilder;
use crate::clock::{SimulationEvent, SIMULATION_PERIOD};
use crate::def::liquid;
use crate::time::Instant;
use crate::units::{self, LiquidVolume};
use crate::{config, def, node, save, util, SetupEcs};
#[derive(Default, getset::MutGetters)]
pub struct RecipeMap {
map: BTreeMap<RecipeKey, liquid::Id>,
default: Option<liquid::Id>,
}
impl RecipeMap {
pub fn define(&mut self, def: &liquid::Formula) -> anyhow::Result<()> {
let key = RecipeKey::new(def.augend(), def.addend());
match self.map.entry(key) {
btree_map::Entry::Vacant(entry) => {
entry.insert(def.sum());
Ok(())
}
btree_map::Entry::Occupied(_) => anyhow::bail!("Duplicate recipe key {:?}", key),
}
}
pub fn define_default(&mut self, def: &liquid::DefaultFormula) -> anyhow::Result<()> {
anyhow::ensure!(self.default.is_none(), "Duplicate default recipe");
self.default = Some(def.sum());
Ok(())
}
pub fn mix(&self, augend: liquid::Id, addend: liquid::Id) -> liquid::Id {
match self.map.get(&RecipeKey::new(augend, addend)) {
Some(&sum) => sum,
None => self.default(),
}
}
pub fn default(&self) -> liquid::Id { self.default.expect("Uninitialized recipe default") }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct RecipeKey {
less: liquid::Id,
greater: liquid::Id,
}
impl RecipeKey {
fn new(a: liquid::Id, b: liquid::Id) -> Self {
if a < b {
Self { less: a, greater: b }
} else {
Self { less: b, greater: a }
}
}
}
#[derive(new, getset::Getters)]
pub struct StorageList {
#[getset(get = "pub")]
storages: SmallVec<[Entity; 4]>,
}
#[derive(new, getset::CopyGetters, getset::Setters)]
pub struct Storage {
#[getset(get_copy = "pub")]
#[getset(set = "pub")]
liquid: liquid::Id,
}
#[derive(Debug, Clone, Copy, new, getset::CopyGetters)]
pub struct StorageCapacity {
#[getset(get_copy = "pub")]
total: LiquidVolume,
}
codegen::component_depends! {
Storage = (
Storage,
StorageCapacity,
StorageSize,
NextStorageType,
NextStorageSize,
def::lang::Item,
node::Child,
) + ?()
}
#[derive(new, getset::CopyGetters)]
pub struct StorageSize {
#[getset(get_copy = "pub")]
size: LiquidVolume,
}
#[derive(new, getset::CopyGetters, getset::Setters)]
pub struct NextStorageType {
#[getset(get_copy = "pub")]
#[getset(set = "pub")]
ty: liquid::Id,
}
#[derive(new, getset::CopyGetters, getset::MutGetters)]
pub struct NextStorageSize {
#[getset(get_copy = "pub")]
#[getset(get_mut = "pub")]
size: LiquidVolume,
}
pub fn lerp(current: &StorageSize, next: &NextStorageSize, time: Instant) -> LiquidVolume {
LiquidVolume(util::lerp(
current.size.value(),
next.size.value(),
(time.since_epoch() % SIMULATION_PERIOD).as_secs() / SIMULATION_PERIOD.as_secs(),
))
}
#[derive(new, getset::CopyGetters)]
pub struct Pipe {
#[getset(get_copy = "pub")]
src_entity: Entity,
#[getset(get_copy = "pub")]
dest_entity: Entity,
}
#[derive(new, getset::CopyGetters)]
pub struct PipeResistance {
#[getset(get_copy = "pub")]
value: f64,
}
impl PipeResistance {
pub fn compute(length: f64, radius: f64) -> Self { Self::new(length / radius.powi(2)) }
}
#[derive(Default, getset::CopyGetters, getset::Setters)]
pub struct PipeFlow {
#[getset(get_copy = "pub")]
#[getset(set = "pub")]
ty: Option<liquid::Id>,
#[getset(get_copy = "pub")]
#[getset(set = "pub")]
value: LiquidVolume,
}
codegen::component_depends! {
Pipe = (
Pipe,
PipeResistance,
PipeFlow,
) + ?()
}
#[derive(Debug, TypedBuilder, getset::CopyGetters)]
pub struct Pump {
#[getset(get_copy = "pub")]
force: units::PipeForce,
}
#[codegen::system(Simulate)]
#[read_component(Pipe)]
#[read_component(PipeResistance)]
#[read_component(Pump)]
#[read_component(Storage)]
#[read_component(StorageCapacity)]
#[read_component(StorageSize)]
#[read_component(node::Child)]
#[write_component(NextStorageSize)]
#[write_component(NextStorageType)]
#[write_component(PipeFlow)]
fn simulate_pipes(
world: &mut SubWorld,
#[resource] config: &config::Scalar,
#[resource(no_init)] def: &save::GameDefinition,
#[subscriber] sim_sub: impl Iterator<Item = SimulationEvent>,
) {
use legion::world::ComponentError;
use legion::{EntityStore, IntoQuery};
if sim_sub.next().is_none() {
return;
}
let mut query = <(&Pipe, &PipeResistance, &mut PipeFlow)>::query();
let (mut query_world, mut entry_world) = world.split_for_query(&query);
for (pipe, resistance, flow) in query.iter_mut(&mut query_world) {
struct FetchEndpoint {
ty: liquid::Id,
force: units::PipeForce,
volume: units::LiquidVolume,
empty: units::LiquidVolume,
viscosity: units::LiquidViscosity,
}
let fetch_endpoint = |storage_entity: Entity| {
let entry = entry_world
.entry_ref(storage_entity)
.expect("Pipe references nonexistent endpoint");
let storage = entry
.get_component::<Storage>()
.expect("Pipe endpoint does not have Storage component");
let ty = storage.liquid();
let parent = entry
.get_component::<node::Child>()
.expect("Pipe endpoint does not have node::Child component");
let parent_entry = entry_world
.entry_ref(parent.parent())
.expect("Storage references nonexistent parent");
let pump = parent_entry.get_component::<Pump>();
let force = match pump {
Ok(pump) => pump.force(),
Err(ComponentError::NotFound { .. }) => units::PipeForce(0.),
Err(ComponentError::Denied { .. }) => unreachable!(),
};
let size = entry
.get_component::<StorageSize>()
.expect("Pipe endpoint does not have StorageSize component");
let capacity = entry
.get_component::<StorageCapacity>()
.expect("Pipe endpoint does not have StorageCapacity component");
let viscosity = def[ty].viscosity();
FetchEndpoint {
ty,
force,
volume: size.size(),
empty: capacity.total() - size.size(),
viscosity,
}
};
let src = fetch_endpoint(pipe.src_entity());
let dest = fetch_endpoint(pipe.dest_entity());
let sum_ty = if src.volume < config.negligible_volume {
dest.ty
} else {
def.liquid_recipes().mix(src.ty, dest.ty)
};
let force = src.force + dest.force;
let mut rate = force.value() / resistance.value() / src.viscosity.value();
rate = rate.min(src.volume.value()).min(dest.empty.value());
let rate = units::LiquidVolume(rate);
flow.set_ty(Some(src.ty));
flow.set_value(rate);
{
let mut src_entity = entry_world
.entry_mut(pipe.src_entity())
.expect("Pipe references nonexistent endpoint");
let next = src_entity
.get_component_mut::<NextStorageSize>()
.expect("Pipe endpoint does not have NextStorageSize component");
*next.size_mut() -= rate;
}
{
let mut dest_entity = entry_world
.entry_mut(pipe.dest_entity())
.expect("Pipe references nonexistent endpoint");
{
let next = dest_entity
.get_component_mut::<NextStorageType>()
.expect("Pipe endpoint does not have NextStorageType component");
next.set_ty(sum_ty);
}
{
let next = dest_entity
.get_component_mut::<NextStorageSize>()
.expect("Pipe endpoint does not have NextStorageSize component");
*next.size_mut() += rate;
}
}
}
}
#[codegen::system(PreSimulate)]
#[write_component(Storage)]
#[write_component(StorageSize)]
#[read_component(NextStorageType)]
#[write_component(NextStorageSize)]
fn update_storage(
world: &mut SubWorld,
#[subscriber] sim_sub: impl Iterator<Item = SimulationEvent>,
) {
use legion::IntoQuery;
if sim_sub.next().is_none() {
return;
}
for (current, next) in <(&mut StorageSize, &NextStorageSize)>::query().iter_mut(world) {
current.size = next.size;
}
for (current, next) in <(&mut Storage, &NextStorageType)>::query().iter_mut(world) {
current.set_liquid(next.ty);
}
}
pub fn setup_ecs(setup: SetupEcs) -> SetupEcs {
setup.uses(simulate_pipes_setup).uses(update_storage_setup)
}