1use glam::Vec2;
24
25use crate::clipmap::{Clipmap, ClipmapConfig};
26use crate::grid::CellKey;
27use crate::hlod::{HlodConfig, HlodDelta, HlodSet};
28use crate::stream::{CellSource, Priority, StreamConfig, Streamer};
29use crate::tier::{Tier, TierPolicy, TierState};
30
31#[derive(Clone, Debug)]
33pub struct PartitionConfig {
34 pub clipmap: ClipmapConfig,
35 pub stream: StreamConfig,
36 pub tiers: TierPolicy,
37 pub tiers_adaptive: bool,
41}
42
43#[derive(Clone, Copy, Debug)]
45pub struct Instance {
46 pub position: Vec2,
47 pub tier: TierState,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub struct TierChange {
53 pub instance: usize,
54 pub from: Tier,
55 pub to: Tier,
56}
57
58#[derive(Debug)]
60pub struct PartitionDelta<P> {
61 pub loaded: Vec<(CellKey, P)>,
63 pub evicted: Vec<CellKey>,
66 pub failed: Vec<CellKey>,
68 pub hlod: HlodDelta,
71 pub tier_changed: Vec<TierChange>,
73}
74
75impl<P> Default for PartitionDelta<P> {
76 fn default() -> Self {
77 Self {
78 loaded: Vec::new(),
79 evicted: Vec::new(),
80 failed: Vec::new(),
81 hlod: HlodDelta::default(),
82 tier_changed: Vec::new(),
83 }
84 }
85}
86
87pub struct WorldPartition<S: CellSource> {
89 cfg: PartitionConfig,
90 clipmap: Clipmap,
91 streamer: Streamer<S>,
92 hlod: HlodSet,
93 instances: Vec<Instance>,
94 time: f64,
95}
96
97impl<S: CellSource> WorldPartition<S> {
98 pub fn new(cfg: PartitionConfig, source: S) -> Self {
99 let clipmap = Clipmap::new(cfg.clipmap);
100 let streamer = Streamer::new(source, cfg.stream);
101 let outer = cfg.clipmap.cell_size(cfg.clipmap.levels - 1);
105 let reach = cfg.clipmap.outer_radius();
106 let hlod = HlodSet::new(HlodConfig {
107 cell_size: outer,
108 take_over: reach,
109 fade_out: reach * 8.0,
110 hysteresis: 0.05,
111 });
112 Self {
113 cfg,
114 clipmap,
115 streamer,
116 hlod,
117 instances: Vec::new(),
118 time: 0.0,
119 }
120 }
121
122 pub fn time(&self) -> f64 {
124 self.time
125 }
126
127 pub fn config(&self) -> &PartitionConfig {
128 &self.cfg
129 }
130
131 pub fn clipmap(&self) -> &Clipmap {
132 &self.clipmap
133 }
134
135 pub fn streamer(&self) -> &Streamer<S> {
136 &self.streamer
137 }
138
139 pub fn hlod(&self) -> &HlodSet {
141 &self.hlod
142 }
143
144 pub fn enable_hlod(&mut self, cfg: HlodConfig) {
147 self.hlod = HlodSet::new(cfg);
148 }
149
150 pub fn hlod_mut(&mut self) -> &mut HlodSet {
152 &mut self.hlod
153 }
154
155 pub fn instances(&self) -> &[Instance] {
156 &self.instances
157 }
158
159 pub fn spawn(&mut self, position: Vec2, camera: Option<Vec2>) -> usize {
162 let dist = camera.map(|c| (position - c).length()).unwrap_or(f32::MAX);
163 let tier = TierState::new(&self.cfg.tiers, dist, self.time as f32);
164 let id = self.instances.len();
165 self.instances.push(Instance { position, tier });
166 id
167 }
168
169 pub fn despawn(&mut self, id: usize) -> Option<Instance> {
172 if id >= self.instances.len() {
173 return None;
174 }
175 Some(self.instances.remove(id))
176 }
177
178 pub fn tier_of(&self, id: usize) -> Option<Tier> {
180 self.instances.get(id).map(|i| i.tier.tier)
181 }
182
183 pub fn set_instance_position(&mut self, id: usize, position: Vec2) -> bool {
187 match self.instances.get_mut(id) {
188 Some(inst) => {
189 inst.position = position;
190 true
191 }
192 None => false,
193 }
194 }
195
196 pub fn update(&mut self, camera: Vec2, dt: f32) -> PartitionDelta<S::Payload> {
201 self.time += dt as f64;
202 self.streamer.set_now(self.time);
203 let mut delta = PartitionDelta::default();
204
205 self.clipmap.set_center(camera);
208
209 if let Some(hd) = self.hlod.update(camera) {
213 delta.hlod = hd;
214 }
215
216 let cells: Vec<(CellKey, Priority)> = self
218 .clipmap
219 .cells()
220 .iter()
221 .map(|a| (a.key, Priority(a.key.level, a.dist_base)))
222 .collect();
223 self.streamer.sync_demand(cells);
224 let sd = self.streamer.drive();
225 delta.loaded = sd.loaded;
226 delta.evicted = sd.evicted;
227 delta.failed = sd.failed;
228
229 let tiers = if self.cfg.tiers_adaptive {
234 self.streamer.telemetry().adapt(&self.cfg.tiers)
235 } else {
236 self.cfg.tiers
237 };
238 for (id, inst) in self.instances.iter_mut().enumerate() {
239 let dist = (inst.position - camera).length();
240 let from = inst.tier.tier;
241 if let Some(to) = tiers.update(&mut inst.tier, dist, self.time as f32) {
242 delta.tier_changed.push(TierChange {
243 instance: id,
244 from,
245 to,
246 });
247 }
248 }
249 delta
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use crate::stream::MockSource;
257
258 fn partition(budget: u64) -> WorldPartition<MockSource> {
259 partition_io(budget, 0.0, 100)
260 }
261
262 fn partition_io(budget: u64, latency: f64, bytes: u64) -> WorldPartition<MockSource> {
265 WorldPartition::new(
266 PartitionConfig {
267 clipmap: ClipmapConfig {
268 base_cell: 64.0,
269 radius: 2,
270 levels: 3,
271 },
272 stream: StreamConfig {
273 budget_bytes: budget,
274 max_inflight: 64,
275 },
276 tiers: TierPolicy::default(),
277 tiers_adaptive: false,
278 },
279 MockSource::new(latency, bytes),
280 )
281 }
282
283 #[test]
284 fn frame_laedt_clipmap_zellen() {
285 let mut p = partition(100_000);
286 let d1 = p.update(Vec2::ZERO, 1.0 / 60.0);
288 assert!(d1.loaded.is_empty(), "Latency 0 heißt nicht sofort fertig");
289 let d2 = p.update(Vec2::ZERO, 1.0 / 60.0);
290 assert!(!d2.loaded.is_empty(), "zweiter Frame macht resident");
291 assert!(p.streamer().resident_bytes() > 0);
292 }
293
294 #[test]
298 fn kameraflug_hinein_wechselt_stufen_monoton() {
299 let mut p = partition(100_000);
300 p.cfg.tiers = TierPolicy {
304 min_dwell: 0.0,
305 ..Default::default()
306 };
307 p.update(Vec2::ZERO, 0.1);
308 let far = p.spawn(Vec2::new(5_000.0, 0.0), Some(Vec2::ZERO));
309 assert_eq!(p.tier_of(far), Some(Tier::T4));
310
311 let mut seq = Vec::new();
312 for i in 0..1800 {
314 let t = i as f32 / 60.0;
315 let cam = Vec2::new((t * 200.0).min(5_000.0), 0.0);
316 let d = p.update(cam, 1.0 / 60.0);
317 for c in d.tier_changed {
318 assert_eq!(c.instance, far);
319 seq.push((c.from, c.to));
320 }
321 }
322 assert_eq!(p.tier_of(far), Some(Tier::T0));
323 assert_eq!(
324 seq,
325 vec![
326 (Tier::T4, Tier::T3),
327 (Tier::T3, Tier::T2),
328 (Tier::T2, Tier::T1),
329 (Tier::T1, Tier::T0),
330 ]
331 );
332 }
333
334 #[test]
338 fn io_adaptive_stufen_reagieren_auf_langsame_platte() {
339 fn fliege(adaptive: bool) -> Tier {
340 let mut p = partition_io(100_000, 0.6, 2 * 1024);
342 p.cfg.tiers_adaptive = adaptive;
343 let inst = p.spawn(Vec2::new(150.0, 0.0), Some(Vec2::ZERO));
344 assert_eq!(p.tier_of(inst), Some(Tier::T2));
345 for i in 0..900 {
347 let cam = Vec2::new(i as f32 / 60.0 * 5.0, 0.0);
348 p.update(cam, 1.0 / 60.0);
349 }
350 let health = p.streamer().telemetry().health();
351 assert!(
352 health < 0.4,
353 "die langsame Quelle muss messbar sein: {health}"
354 );
355 p.tier_of(inst).unwrap()
356 }
357 assert_eq!(fliege(false), Tier::T1, "Basis-Regel: bei 75 m ist T1 frei");
358 assert_eq!(
359 fliege(true),
360 Tier::T2,
361 "langsame Platte: T1 bleibt gesperrt"
362 );
363 }
364
365 #[test]
366 fn despawn_entfernt_und_schiebt_nach() {
367 let mut p = partition(100_000);
368 p.update(Vec2::ZERO, 0.1);
369 let a = p.spawn(Vec2::new(1.0, 1.0), Some(Vec2::ZERO));
370 let b = p.spawn(Vec2::new(2.0, 2.0), Some(Vec2::ZERO));
371 assert_eq!((a, b), (0, 1));
372 let gone = p.despawn(a).expect("Index 0 existiert");
373 assert_eq!(gone.position, Vec2::new(1.0, 1.0));
374 assert_eq!(p.instances().len(), 1);
375 assert_eq!(p.instances()[0].position, Vec2::new(2.0, 2.0));
377 assert!(p.despawn(5).is_none(), "außerhalb ist None");
378 }
379
380 #[test]
383 fn fassade_ist_deterministisch() {
384 fn run() -> Vec<(Vec<String>, Vec<TierChange>)> {
385 let mut p = partition(4_000);
386 let mut log = Vec::new();
387 p.update(Vec2::ZERO, 0.5);
388 p.spawn(Vec2::new(60.0, 0.0), Some(Vec2::ZERO));
389 p.spawn(Vec2::new(0.0, 900.0), Some(Vec2::ZERO));
390 for i in 0..240 {
391 let t = i as f32 / 60.0;
392 let cam = Vec2::new(t * 400.0, t * 50.0);
393 let d = p.update(cam, 1.0 / 60.0);
394 let mut ev: Vec<String> = Vec::new();
395 for (k, _) in &d.loaded {
396 ev.push(format!("L {k:?}"));
397 }
398 for k in &d.evicted {
399 ev.push(format!("E {k:?}"));
400 }
401 for k in &d.failed {
402 ev.push(format!("F {k:?}"));
403 }
404 log.push((ev, d.tier_changed));
405 }
406 log
407 }
408 let a = run();
409 let b = run();
410 assert_eq!(a.len(), b.len());
411 let events: usize = a.iter().map(|(e, t)| e.len() + t.len()).sum();
413 assert!(
414 events > 20,
415 "Skript erzeugt messbar viel Betrieb ({events})"
416 );
417 for (fa, fb) in a.iter().zip(&b) {
418 assert_eq!(fa.0, fb.0, "Zell-Ereignisse pro Frame identisch");
419 assert_eq!(fa.1, fb.1, "Stufenwechsel pro Frame identisch");
420 }
421 }
422
423 #[test]
427 fn partition_treibt_hlod_cluster() {
428 let mut p = partition(1 << 30); assert!(
430 p.update(Vec2::ZERO, 0.1).hlod.is_empty(),
431 "ohne Bake bleibt es leer"
432 );
433
434 let fern = crate::hlod::HlodCell { x: 4, y: 0 }; p.hlod_mut().register(fern, 64);
436 let d = p.update(Vec2::ZERO, 0.1);
437 assert_eq!(d.hlod.shown, vec![fern]);
438
439 let d = p.update(Vec2::new(1_100.0, 0.0), 0.1);
441 assert_eq!(d.hlod.hidden, vec![fern]);
442 assert!(p.update(Vec2::new(1_100.0, 0.0), 0.1).hlod.is_empty());
443 }
444}