1use std::sync::{Arc, Mutex, MutexGuard};
19
20use glam::Vec2;
21use serde_json::json;
22
23use crate::capability::{CapabilityRegistry, ToolSpec};
24use re_world::{CellSource, WorldPartition};
25
26pub struct WorldSession<S: CellSource> {
30 pub partition: WorldPartition<S>,
31 pub camera: Vec2,
33}
34
35impl<S: CellSource> WorldSession<S> {
36 pub fn new(partition: WorldPartition<S>, camera: Vec2) -> Self {
37 Self { partition, camera }
38 }
39}
40
41pub type SharedWorld<S> = Arc<Mutex<WorldSession<S>>>;
43
44fn lock<S: CellSource>(world: &SharedWorld<S>) -> Result<MutexGuard<'_, WorldSession<S>>, String> {
47 world
48 .lock()
49 .map_err(|_| "Welt-Sperre vergiftet — vorheriger Aufruf gepanikt".to_string())
50}
51
52fn arg_f32(args: &serde_json::Value, key: &str) -> Result<f32, String> {
53 args.get(key)
54 .and_then(|v| v.as_f64())
55 .map(|v| v as f32)
56 .ok_or_else(|| format!("Parameter '{key}' fehlt (Zahl erwartet)"))
57}
58
59fn arg_usize(args: &serde_json::Value, key: &str) -> Result<usize, String> {
60 args.get(key)
61 .and_then(|v| v.as_u64())
62 .map(|v| v as usize)
63 .ok_or_else(|| format!("Parameter '{key}' fehlt (Ganzzahl erwartet)"))
64}
65
66const LIST_CAP: usize = 512;
68
69pub fn register_world_tools<S>(reg: &mut CapabilityRegistry, world: SharedWorld<S>)
72where
73 S: CellSource + Send + 'static,
74 S::Payload: Send,
75{
76 {
78 let w = Arc::clone(&world);
79 reg.register(
80 ToolSpec::simple(
81 "world.stats",
82 "Welt-Überblick: Zeit, Kamera, Zell-Bestand, IO-Telemetrie, HLOD, Instanzen",
83 ),
84 move |_| {
85 let s = lock(&w)?;
86 let p = &s.partition;
87 let t = p.streamer().telemetry();
88 let cm = p.clipmap().config();
89 Ok(json!({
90 "zeit": p.time(),
91 "kamera": { "x": s.camera.x, "z": s.camera.y },
92 "clipmap": {
93 "ebenen": cm.levels,
94 "basiszelle": cm.base_cell,
95 "reichweite": cm.outer_radius(),
96 "aktive_zellen": p.clipmap().cells().len(),
97 },
98 "streamer": {
99 "resident_zellen": p.streamer().resident().len(),
100 "resident_bytes": p.streamer().resident_bytes(),
101 },
102 "io_telemetrie": {
103 "lasten": t.samples(),
104 "fehler": t.failures(),
105 "latenz_ms": t.latency_ewma() * 1000.0,
106 "durchsatz_mibs": t.throughput_ewma() / (1024.0 * 1024.0),
107 "gesundheit": t.health(),
108 },
109 "hlod": {
110 "cluster": p.hlod().len(),
111 "sichtbar": p.hlod().shown().len(),
112 },
113 "instanzen": p.instances().len(),
114 }))
115 },
116 );
117 }
118 {
119 let w = Arc::clone(&world);
120 reg.register(
121 ToolSpec::new(
122 "world.cells.resident",
123 "Residente Zellen auflisten (optional nach Ebene gefiltert)",
124 json!({ "typ": "object", "felder": { "ebene": { "typ": "integer" } } }),
125 ),
126 move |args| {
127 let s = lock(&w)?;
128 let level = args.get("ebene").and_then(|v| v.as_u64()).map(|v| v as u8);
129 let mut out = Vec::new();
130 let mut total = 0usize;
131 for (key, bytes) in s.partition.streamer().resident() {
132 if level.is_some_and(|l| key.level != l) {
133 continue;
134 }
135 total += 1;
136 if out.len() < LIST_CAP {
137 out.push(
138 json!({ "ebene": key.level, "x": key.x, "z": key.y, "bytes": bytes }),
139 );
140 }
141 }
142 Ok(json!({ "zellen": out, "anzahl": total, "gekuerzt": total > out.len() }))
143 },
144 );
145 }
146 {
147 let w = Arc::clone(&world);
148 reg.register(
149 ToolSpec::new(
150 "world.cell.state",
151 "Streaming-Zustand einer Zelle: queued|loading|ready|none",
152 json!({ "typ": "object", "felder": {
153 "ebene": { "typ": "integer" }, "x": { "typ": "integer" }, "z": { "typ": "integer" }
154 } }),
155 ),
156 move |args| {
157 let s = lock(&w)?;
158 let level = args
159 .get("ebene")
160 .and_then(|v| v.as_u64())
161 .map(|v| v as u8)
162 .ok_or("Parameter 'ebene' fehlt (Ganzzahl erwartet)")?;
163 let key = re_world::CellKey {
164 level,
165 x: arg_usize_i64(&args, "x")?,
166 y: arg_usize_i64(&args, "z")?,
167 };
168 let state = match s.partition.streamer().state_of(key) {
169 Some(re_world::SlotState::Queued) => "queued",
170 Some(re_world::SlotState::Loading) => "loading",
171 Some(re_world::SlotState::Ready) => "ready",
172 None => "none",
173 };
174 Ok(json!({ "zustand": state }))
175 },
176 );
177 }
178 {
179 let w = Arc::clone(&world);
180 reg.register(
181 ToolSpec::new(
182 "world.hlod.list",
183 "HLOD-Cluster auflisten (nur sichtbare auf Wunsch)",
184 json!({ "typ": "object", "felder": { "nur_sichtbare": { "typ": "boolean" } } }),
185 ),
186 move |args| {
187 let s = lock(&w)?;
188 let shown_only = args
189 .get("nur_sichtbare")
190 .and_then(|v| v.as_bool())
191 .unwrap_or(false);
192 let hl = s.partition.hlod();
193 let mut out = Vec::new();
194 for c in hl.shown() {
195 if out.len() >= LIST_CAP {
196 break;
197 }
198 out.push(json!({
199 "x": c.x, "z": c.y,
200 "quellzellen": hl.source_cells(c).unwrap_or(0),
201 }));
202 }
203 if !shown_only {
204 for cell in hl.cells() {
206 if out.len() >= LIST_CAP {
207 break;
208 }
209 if !hl.is_shown(cell) {
210 out.push(json!({
211 "x": cell.x, "z": cell.y,
212 "quellzellen": hl.source_cells(cell).unwrap_or(0),
213 }));
214 }
215 }
216 }
217 Ok(json!({ "cluster": out, "anzahl": hl.len() }))
218 },
219 );
220 }
221 {
222 let w = Arc::clone(&world);
223 reg.register(
224 ToolSpec::simple(
225 "world.instances.list",
226 "Alle Instanzen mit Position und Qualitätsstufe",
227 ),
228 move |_| {
229 let s = lock(&w)?;
230 let out: Vec<_> = s
231 .partition
232 .instances()
233 .iter()
234 .enumerate()
235 .take(LIST_CAP)
236 .map(|(id, inst)| {
237 json!({
238 "id": id,
239 "x": inst.position.x,
240 "z": inst.position.y,
241 "stufe": format!("{:?}", inst.tier.tier),
242 })
243 })
244 .collect();
245 Ok(json!({ "instanzen": out, "anzahl": s.partition.instances().len() }))
246 },
247 );
248 }
249
250 {
252 let w = Arc::clone(&world);
253 reg.register(
254 ToolSpec::new(
255 "world.camera.set",
256 "Kamera-Anker setzen (wirkt auf den nächsten world.tick)",
257 json!({ "typ": "object", "felder": { "x": { "typ": "number" }, "z": { "typ": "number" } } }),
258 ),
259 move |args| {
260 let mut s = lock(&w)?;
261 s.camera = Vec2::new(arg_f32(&args, "x")?, arg_f32(&args, "z")?);
262 Ok(json!({ "kamera": { "x": s.camera.x, "z": s.camera.y } }))
263 },
264 );
265 }
266 {
267 let w = Arc::clone(&world);
268 reg.register(
269 ToolSpec::new(
270 "world.tick",
271 "Welt einen Schritt weiterschieben (dt Sekunden); liefert die Ereigniszahlen des Schritts",
272 json!({ "typ": "object", "felder": { "dt": { "typ": "number" } } }),
273 ),
274 move |args| {
275 let mut s = lock(&w)?;
276 let dt = arg_f32(&args, "dt")?;
277 if !(dt.is_finite() && dt >= 0.0) {
278 return Err("dt muss eine endliche, nicht-negative Zahl sein".into());
279 }
280 let delta = {
281 let cam = s.camera; s.partition.update(cam, dt)
283 };
284 Ok(json!({
285 "geladen": delta.loaded.len(),
286 "verdraengt": delta.evicted.len(),
287 "fehlgeschlagen": delta.failed.len(),
288 "stufenwechsel": delta.tier_changed.len(),
289 "hlod_uebernommen": delta.hlod.shown.len(),
290 "hlod_zurueck": delta.hlod.hidden.len(),
291 }))
292 },
293 );
294 }
295 {
296 let w = Arc::clone(&world);
297 reg.register(
298 ToolSpec::new(
299 "world.instance.spawn",
300 "Instanz in die Welt setzen; liefert ihre id",
301 json!({ "typ": "object", "felder": { "x": { "typ": "number" }, "z": { "typ": "number" } } }),
302 ),
303 move |args| {
304 let mut s = lock(&w)?;
305 let pos = Vec2::new(arg_f32(&args, "x")?, arg_f32(&args, "z")?);
306 let cam = Some(s.camera); let id = s.partition.spawn(pos, cam);
308 Ok(json!({ "id": id, "x": pos.x, "z": pos.y }))
309 },
310 );
311 }
312 {
313 let w = Arc::clone(&world);
314 reg.register(
315 ToolSpec::new(
316 "world.instance.move",
317 "Instanz umsetzen (Stufenneubewertung im nächsten Tick)",
318 json!({ "typ": "object", "felder": {
319 "id": { "typ": "integer" }, "x": { "typ": "number" }, "z": { "typ": "number" }
320 } }),
321 ),
322 move |args| {
323 let mut s = lock(&w)?;
324 let id = arg_usize(&args, "id")?;
325 let pos = Vec2::new(arg_f32(&args, "x")?, arg_f32(&args, "z")?);
326 if s.partition.set_instance_position(id, pos) {
327 Ok(json!({ "ok": true, "id": id }))
328 } else {
329 Err(format!("keine Instanz mit id {id}"))
330 }
331 },
332 );
333 }
334 {
335 let w = Arc::clone(&world);
336 reg.register(
337 ToolSpec::new(
338 "world.instance.remove",
339 "Instanz aus der Welt nehmen",
340 json!({ "typ": "object", "felder": { "id": { "typ": "integer" } } }),
341 ),
342 move |args| {
343 let mut s = lock(&w)?;
344 let id = arg_usize(&args, "id")?;
345 match s.partition.despawn(id) {
346 Some(inst) => {
347 Ok(json!({ "ok": true, "x": inst.position.x, "z": inst.position.y }))
348 }
349 None => Err(format!("keine Instanz mit id {id}")),
350 }
351 },
352 );
353 }
354}
355
356fn arg_usize_i64(args: &serde_json::Value, key: &str) -> Result<i64, String> {
358 args.get(key)
359 .and_then(|v| v.as_i64())
360 .ok_or_else(|| format!("Parameter '{key}' fehlt (Ganzzahl erwartet)"))
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366 use re_world::{ClipmapConfig, MockSource, PartitionConfig, StreamConfig, TierPolicy};
367 use serde_json::json;
368
369 fn session() -> SharedWorld<MockSource> {
370 let partition = WorldPartition::new(
371 PartitionConfig {
372 clipmap: ClipmapConfig {
373 base_cell: 64.0,
374 radius: 2,
375 levels: 3,
376 },
377 stream: StreamConfig {
378 budget_bytes: 100_000,
379 max_inflight: 64,
380 },
381 tiers: TierPolicy::default(),
382 tiers_adaptive: false,
383 },
384 MockSource::new(0.0, 100),
385 );
386 Arc::new(Mutex::new(WorldSession::new(partition, Vec2::ZERO)))
387 }
388
389 fn rig() -> CapabilityRegistry {
390 let mut reg = CapabilityRegistry::new();
391 register_world_tools(&mut reg, session());
392 reg
393 }
394
395 #[test]
396 fn alle_werkzeuge_sind_registriert() {
397 let reg = rig();
398 for name in [
399 "world.stats",
400 "world.cells.resident",
401 "world.cell.state",
402 "world.hlod.list",
403 "world.instances.list",
404 "world.camera.set",
405 "world.tick",
406 "world.instance.spawn",
407 "world.instance.move",
408 "world.instance.remove",
409 ] {
410 assert!(reg.has(name), "fehlt: {name}");
411 }
412 }
413
414 #[test]
415 fn spawn_bewegen_entfernen_ueber_die_registry() {
416 let reg = rig();
417 let id = reg
418 .call("world.instance.spawn", json!({ "x": 10.0, "z": 20.0 }))
419 .unwrap()["id"]
420 .as_u64()
421 .unwrap();
422 let list = reg.call("world.instances.list", json!({})).unwrap();
423 assert_eq!(list["anzahl"], json!(1));
424 assert_eq!(list["instanzen"][0]["x"], json!(10.0));
425 reg.call(
426 "world.instance.move",
427 json!({ "id": id, "x": 30.0, "z": 40.0 }),
428 )
429 .unwrap();
430 let list = reg.call("world.instances.list", json!({})).unwrap();
431 assert_eq!(list["instanzen"][0]["x"], json!(30.0));
432 reg.call("world.instance.remove", json!({ "id": id }))
433 .unwrap();
434 assert_eq!(
435 reg.call("world.instances.list", json!({})).unwrap()["anzahl"],
436 json!(0)
437 );
438 assert!(reg
440 .call(
441 "world.instance.move",
442 json!({ "id": 99, "x": 0.0, "z": 0.0 })
443 )
444 .is_err());
445 }
446
447 #[test]
448 fn kamera_und_tick_bewegen_die_welt() {
449 let reg = rig();
450 reg.call("world.camera.set", json!({ "x": 500.0, "z": 0.0 }))
451 .unwrap();
452 let stats = reg.call("world.stats", json!({})).unwrap();
453 assert_eq!(stats["kamera"]["x"], json!(500.0));
454 let t1 = reg.call("world.tick", json!({ "dt": 0.016 })).unwrap();
457 let t2 = reg.call("world.tick", json!({ "dt": 0.016 })).unwrap();
458 let geladen = t1["geladen"].as_u64().unwrap() + t2["geladen"].as_u64().unwrap();
459 assert!(geladen > 0, "Zellen wurden geladen");
460 let resident = reg.call("world.cells.resident", json!({})).unwrap();
461 assert!(resident["anzahl"].as_u64().unwrap() > 0);
462 let z = &resident["zellen"][0];
464 let state = reg
465 .call(
466 "world.cell.state",
467 json!({ "ebene": z["ebene"], "x": z["x"], "z": z["z"] }),
468 )
469 .unwrap();
470 assert_eq!(state["zustand"], json!("ready"));
471 let state = reg
473 .call(
474 "world.cell.state",
475 json!({ "ebene": 0, "x": 99999, "z": 99999 }),
476 )
477 .unwrap();
478 assert_eq!(state["zustand"], json!("none"));
479 }
480
481 #[test]
482 fn fehlerpfade_sind_sauber() {
483 let reg = rig();
484 assert!(reg.call("world.camera.set", json!({ "x": 1.0 })).is_err());
486 assert!(reg.call("world.tick", json!({ "dt": -1.0 })).is_err());
488 assert!(reg.call("world.es_gibt_mich_nicht", json!({})).is_err());
490 }
491
492 #[test]
493 fn stats_zaehlen_mit() {
494 let reg = rig();
495 reg.call("world.instance.spawn", json!({ "x": 0.0, "z": 0.0 }))
496 .unwrap();
497 reg.call("world.tick", json!({ "dt": 0.016 })).unwrap();
498 let stats = reg.call("world.stats", json!({})).unwrap();
499 assert_eq!(stats["instanzen"], json!(1));
500 assert!(stats["clipmap"]["aktive_zellen"].as_u64().unwrap() > 0);
501 assert_eq!(stats["io_telemetrie"]["fehler"], json!(0));
502 assert_eq!(
503 stats["hlod"]["cluster"],
504 json!(0),
505 "ohne Bake keine Cluster"
506 );
507 assert_eq!(
508 reg.call("world.hlod.list", json!({})).unwrap()["anzahl"],
509 json!(0)
510 );
511 }
512}