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
use std::{collections::VecDeque, sync::Arc};
use crossbeam_channel::{unbounded, Receiver, Sender, TryRecvError};
use hashbrown::{HashMap, HashSet};
use rayon::{ThreadPool, ThreadPoolBuilder};
use crate::{BlockChange, Chunk, Registry, Space, SpaceData, Vec2, Vec3, VoxelAccess, WorldConfig};
use super::{noise::SeededNoise, terrain::SeededTerrain};
#[derive(Default)]
pub struct ResourceRequirements {
pub needs_registry: bool,
pub needs_config: bool,
pub needs_noise: bool,
pub needs_terrain: bool,
}
#[derive(Default)]
pub struct ResourceResults<'a> {
pub registry: Option<&'a Registry>,
pub config: Option<&'a WorldConfig>,
pub noise: Option<&'a SeededNoise>,
pub terrain: Option<&'a SeededTerrain>,
}
pub trait ChunkStage {
fn name(&self) -> String;
fn neighbors(&self, _: &WorldConfig) -> usize {
0
}
fn needs_space(&self) -> Option<SpaceData> {
None
}
fn needs_resources(&self) -> ResourceRequirements {
ResourceRequirements {
needs_registry: true,
..Default::default()
}
}
fn process(&self, chunk: Chunk, resources: ResourceResults, space: Option<Space>) -> Chunk;
}
pub struct HeightMapStage;
impl ChunkStage for HeightMapStage {
fn name(&self) -> String {
"HeightMap".to_owned()
}
fn process(&self, mut chunk: Chunk, resources: ResourceResults, _: Option<Space>) -> Chunk {
chunk.calculate_max_height(resources.registry.unwrap());
chunk
}
}
pub struct FlatlandStage {
height: i32,
top: u32,
middle: u32,
bottom: u32,
}
impl FlatlandStage {
pub fn new(height: i32, top: u32, middle: u32, bottom: u32) -> Self {
Self {
height,
top,
middle,
bottom,
}
}
}
impl ChunkStage for FlatlandStage {
fn name(&self) -> String {
"Flatland".to_owned()
}
fn process(&self, mut chunk: Chunk, _: ResourceResults, _: Option<Space>) -> Chunk {
let Vec3(min_x, _, min_z) = chunk.min;
let Vec3(max_x, _, max_z) = chunk.max;
for vx in min_x..max_x {
for vz in min_z..max_z {
for vy in 0..self.height {
if vy == 0 {
chunk.set_voxel(vx, vy, vz, self.bottom);
} else if vy == self.height - 1 {
chunk.set_voxel(vx, vy, vz, self.top);
} else {
chunk.set_voxel(vx, vy, vz, self.middle);
}
}
}
}
chunk
}
}
pub struct Pipeline {
pub chunks: HashSet<Vec2<i32>>,
pub leftovers: HashMap<Vec2<i32>, Vec<BlockChange>>,
sender: Arc<Sender<(Vec<Chunk>, Vec<BlockChange>)>>,
receiver: Arc<Receiver<(Vec<Chunk>, Vec<BlockChange>)>>,
pool: ThreadPool,
queue: VecDeque<(Vec2<i32>, usize)>,
stages: Vec<Arc<dyn ChunkStage + Send + Sync>>,
}
impl Pipeline {
pub fn new() -> Self {
let (sender, receiver) = unbounded();
Self {
chunks: HashSet::default(),
leftovers: HashMap::default(),
sender: Arc::new(sender),
receiver: Arc::new(receiver),
pool: ThreadPoolBuilder::new()
.thread_name(|index| format!("voxelize-chunking-{index}"))
.build()
.unwrap(),
queue: VecDeque::default(),
stages: vec![],
}
}
pub fn has(&self, coords: &Vec2<i32>) -> bool {
self.chunks.contains(coords)
}
pub fn len(&self) -> usize {
self.stages.len()
}
pub fn push(&mut self, coords: &Vec2<i32>, index: usize) {
if self.stages.is_empty() {
return;
}
assert!(index < self.stages.len());
if self.has(coords) {
return;
}
self.chunks.insert(coords.to_owned());
self.queue.push_back((coords.to_owned(), index));
}
pub fn pop(&mut self) -> Option<(Vec2<i32>, usize)> {
self.queue.pop_front()
}
pub fn postpone(&mut self, coords: &Vec2<i32>, index: usize) {
self.queue.iter().for_each(|(c, _)| {
if *coords == *c {
panic!("Chunk {:?} is already waiting in queue.", coords);
}
});
self.chunks.remove(&coords);
self.push(coords, index);
}
pub fn add_stage<T>(&mut self, stage: T)
where
T: 'static + ChunkStage + Send + Sync,
{
self.stages.push(Arc::new(stage));
}
pub fn get_stage(&mut self, index: usize) -> &Arc<dyn ChunkStage + Send + Sync> {
&self.stages[index]
}
pub fn process(
&mut self,
processes: Vec<(Chunk, Option<Space>, usize)>,
registry: &Registry,
config: &WorldConfig,
noise: &SeededNoise,
terrain: &SeededTerrain,
) {
let processes: Vec<(Chunk, Option<Space>, Arc<dyn ChunkStage + Send + Sync>)> = processes
.into_iter()
.map(|(chunk, space, index)| {
let stage = self.stages.get(index).unwrap().clone();
(chunk, space, stage)
})
.collect();
let sender = Arc::clone(&self.sender);
let registry = registry.to_owned();
let config = config.to_owned();
let noise = noise.to_owned();
let terrain = terrain.to_owned();
self.pool.spawn(move || {
let mut changes = vec![];
let chunks: Vec<Chunk> = processes
.into_iter()
.map(|(chunk, space, stage)| {
let resources = stage.needs_resources();
let mut chunk = stage.process(
chunk,
{
let ResourceRequirements {
needs_registry,
needs_config,
needs_noise,
needs_terrain,
} = resources;
ResourceResults {
registry: if needs_registry {
Some(®istry)
} else {
None
},
config: if needs_config { Some(&config) } else { None },
noise: if needs_noise { Some(&noise) } else { None },
terrain: if needs_terrain { Some(&terrain) } else { None },
}
},
space,
);
if !chunk.exceeded_changes.is_empty() {
changes.append(&mut chunk.exceeded_changes.drain(..).collect());
}
chunk
})
.collect();
sender.send((chunks, changes)).unwrap();
});
}
pub fn results(&self) -> Result<(Vec<Chunk>, Vec<BlockChange>), TryRecvError> {
self.receiver.try_recv()
}
pub fn advance(&mut self, chunk: &mut Chunk) {
if !self.chunks.contains(&chunk.coords) {
panic!("Chunk {:?} isn't in the pipeline.", chunk.coords);
}
if chunk.stage.is_none() {
panic!(
"Something's wrong! Why does chunk {:?} not have a stage?",
chunk.coords
);
}
let index = chunk.stage.unwrap();
if index == self.stages.len() - 1 {
chunk.stage = None;
self.remove(&chunk.coords);
return;
}
chunk.stage = Some(index + 1);
self.queue.push_back((chunk.coords.to_owned(), index + 1));
}
pub fn remove(&mut self, coords: &Vec2<i32>) {
self.chunks.remove(&coords);
}
pub fn is_empty(&self) -> bool {
self.chunks.is_empty() || self.queue.is_empty()
}
pub fn get_stage_name(&self, index: Option<usize>) -> Option<String> {
if index.is_none() {
return None;
}
let index = index.unwrap();
if let Some(stage) = self.stages.get(index) {
return Some(stage.name());
}
None
}
}