1use std::sync::mpsc::channel;
2
3use rapier2d::prelude::*;
4use serde::{Deserialize, Serialize};
5
6use crate::nav::navigation::NavigationSystem;
7use crate::nav::spatial::SpatialGrid;
8use crate::config::{EngineConfig, PLAYER_STATE_LEN};
9use crate::events::CoreEvent;
10use crate::map::{GameMap, MapConfig};
11use crate::rng::Rng;
12use crate::sim::{GameDef, GameSim, SimCtx};
13use crate::snapshot::Block;
14
15const MAX_ACCUMULATED_TIME: f32 = 0.1;
17
18pub struct EngineSim<G: GameDef> {
26 pub cfg: EngineConfig,
27 pub world: PhysicsWorld,
28 pub map: Option<GameMap>,
29 pub nav: Option<NavigationSystem>,
30 pub spatial: SpatialGrid,
31 pub rng: Rng,
32
33 time_step: f32,
34 accumulator: f32,
35
36 pub events: Vec<CoreEvent>,
38
39 bodies_to_destroy: Vec<RigidBodyHandle>,
41
42 last_body_has_events: bool,
45
46 pub sim: G::Sim,
47}
48
49impl<G: GameDef> EngineSim<G> {
50 pub fn new(cfg: EngineConfig, game_cfg: &G::Config) -> Self {
51 let time_step = cfg.time_step;
52
53 let mut world = PhysicsWorld::new();
54
55 world.gravity = Vector::ZERO;
56 world.integration_parameters.dt = time_step;
57
58 let seed = cfg.seed;
59 let sim = G::Sim::new(game_cfg, &cfg);
60
61 Self {
62 world,
63 map: None,
64 nav: None,
65 spatial: SpatialGrid::new(600.0),
66 rng: Rng::new(seed),
67 time_step,
68 accumulator: 0.0,
69 events: Vec::new(),
70 bodies_to_destroy: Vec::new(),
71 last_body_has_events: false,
72 sim,
73 cfg,
74 }
75 }
76
77 pub fn load_map(&mut self, json: &str) -> Result<(), String> {
81 let map_cfg: MapConfig = serde_json::from_str(json).map_err(|e| format!("bad map json: {e}"))?;
82
83 if let Some(mut old) = self.map.take() {
84 old.destroy(&mut self.world);
85 }
86
87 let map = GameMap::create(&mut self.world, &map_cfg, self.cfg.map_scale, &self.cfg.map_set_id);
88
89 self.nav = Some(NavigationSystem::generate(&map.grid, &map.physics_static, map.step));
90 self.map = Some(map);
91
92 Ok(())
93 }
94
95 pub fn map_info_json(&self) -> String {
98 let Some(map) = &self.map else {
99 return "null".to_string();
100 };
101
102 let width = map.grid.first().map(|row| row.len()).unwrap_or(0) as f32 * map.step;
103 let height = map.grid.len() as f32 * map.step;
104
105 serde_json::json!({
106 "setId": map.set_id,
107 "step": map.step,
108 "width": width,
109 "height": height,
110 "respawns": map.respawns,
111 })
112 .to_string()
113 }
114
115 pub fn spawn_actor(&mut self, game_id: u32, model_name: &str, team_id: u8, x: f32, y: f32, angle_deg: f32) -> Result<(), String> {
118 self.sim
119 .spawn_actor(&mut self.world, &mut self.events, game_id, model_name, team_id, x, y, angle_deg)
120 }
121
122 pub fn remove_actor(&mut self, game_id: u32) {
123 self.sim.remove_actor(&mut self.world, game_id);
124 }
125
126 pub fn reset_actor(&mut self, game_id: u32, team_id: u8, x: f32, y: f32, angle_deg: f32) {
127 self.sim.reset_actor(&mut self.world, game_id, team_id, x, y, angle_deg);
128 }
129
130 pub fn reset_all_vitals(&mut self) {
131 self.sim.reset_all_vitals(&mut self.events);
132 }
133
134 pub fn spawn_scripted_actor(&mut self, game_id: u32, model_name: &str, team_id: u8, x: f32, y: f32, angle_deg: f32) -> Result<(), String> {
135 self.sim.spawn_scripted_actor(
136 &mut self.world,
137 &mut self.rng,
138 &mut self.events,
139 game_id,
140 model_name,
141 team_id,
142 x,
143 y,
144 angle_deg,
145 )
146 }
147
148 pub fn remove_scripted_actor(&mut self, game_id: u32) {
149 self.sim.remove_scripted_actor(&mut self.world, game_id);
150 }
151
152 pub fn apply_input(&mut self, game_id: u32, seq: u32, action: &str, key_name: &str) {
155 self.sim.apply_input(game_id, seq, action, key_name);
156 }
157
158 pub fn last_input_seq(&self, game_id: u32) -> u32 {
159 self.sim.last_input_seq(game_id)
160 }
161
162 pub fn take_events_json(&mut self) -> String {
165 let events: Vec<CoreEvent> = self.events.drain(..).collect();
166
167 serde_json::to_string(&events).unwrap_or_else(|_| "[]".to_string())
168 }
169
170 pub fn is_alive(&self, game_id: u32) -> bool {
173 self.sim.is_alive(game_id)
174 }
175
176 pub fn actor_position(&self, game_id: u32) -> Option<[f32; 2]> {
177 self.sim.actor_position(&self.world, game_id)
178 }
179
180 pub fn prediction_state(&self, game_id: u32) -> Option<([f32; PLAYER_STATE_LEN], bool)> {
181 self.sim.prediction_state(&self.world, game_id)
182 }
183
184 pub fn alive_players_flat(&self) -> Vec<f32> {
185 self.sim.alive_players_flat(&self.world)
186 }
187
188 pub fn players_json(&self) -> String {
191 self.sim.players_json()
192 }
193
194 pub fn step(&mut self, dt: f32) {
199 self.accumulator = (self.accumulator + dt).min(MAX_ACCUMULATED_TIME);
200
201 while self.accumulator >= self.time_step {
202 self.step_fixed();
203 self.accumulator -= self.time_step;
204 }
205
206 self.sim.refresh_cached(&self.world);
207
208 let mut ctx = SimCtx {
209 world: &mut self.world,
210 cfg: &self.cfg,
211 map: &self.map,
212 nav: &self.nav,
213 spatial: &mut self.spatial,
214 rng: &mut self.rng,
215 events: &mut self.events,
216 bodies_to_destroy: &mut self.bodies_to_destroy,
217 };
218
219 self.sim.on_ai_tick(&mut ctx, dt);
220 }
221
222 fn step_fixed(&mut self) {
224 let mut ctx = SimCtx {
225 world: &mut self.world,
226 cfg: &self.cfg,
227 map: &self.map,
228 nav: &self.nav,
229 spatial: &mut self.spatial,
230 rng: &mut self.rng,
231 events: &mut self.events,
232 bodies_to_destroy: &mut self.bodies_to_destroy,
233 };
234
235 self.sim.on_fixed_step(&mut ctx, self.time_step);
236
237 let (collision_send, collision_recv) = channel();
239 let (force_send, _force_recv) = channel();
240 let collector = ChannelEventCollector::new(collision_send, force_send);
241
242 self.world.step_with_events(&(), &collector);
243
244 let mut contacts = Vec::new();
245
246 while let Ok(event) = collision_recv.try_recv() {
247 if let CollisionEvent::Started(h1, h2, _) = event {
248 contacts.push((h1, h2));
249 }
250 }
251
252 let mut ctx = SimCtx {
253 world: &mut self.world,
254 cfg: &self.cfg,
255 map: &self.map,
256 nav: &self.nav,
257 spatial: &mut self.spatial,
258 rng: &mut self.rng,
259 events: &mut self.events,
260 bodies_to_destroy: &mut self.bodies_to_destroy,
261 };
262
263 self.sim.on_contacts(&mut ctx, &contacts);
264 self.destroy_queued_bodies();
265 }
266
267 fn destroy_queued_bodies(&mut self) {
269 if self.bodies_to_destroy.is_empty() {
270 return;
271 }
272
273 let handles: Vec<RigidBodyHandle> = self.bodies_to_destroy.drain(..).collect();
274
275 for handle in handles {
276 self.sim.on_before_destroy(&self.world, handle);
277 self.world.remove_body(handle);
278 }
279 }
280
281 pub fn build_snapshot_blocks(&mut self) -> Vec<(String, Block)> {
286 let (mut blocks, has_events) = self.sim.build_snapshot_blocks();
287
288 if let Some(map) = &self.map {
290 blocks.push((
291 map.set_id.clone(),
292 Block::IndexedNoNull8(map.dynamic_map_data(&self.world)),
293 ));
294 }
295
296 self.last_body_has_events = has_events;
297
298 blocks
299 }
300
301 pub fn body_has_events(&self) -> bool {
304 self.last_body_has_events
305 }
306
307 pub fn remove_players_and_shots(&mut self) -> Vec<String> {
312 self.sim.remove_players_and_shots(&mut self.world)
313 }
314
315 pub fn clear(&mut self) {
317 if let Some(mut map) = self.map.take() {
320 map.destroy(&mut self.world);
321 }
322
323 let handles: Vec<RigidBodyHandle> = self.world.rigid_bodies().map(|(handle, _)| handle).collect();
324
325 for handle in handles {
326 self.world.remove_body(handle);
327 }
328
329 self.sim.clear();
330 self.nav = None;
331 self.spatial.clear();
332 self.bodies_to_destroy.clear();
333
334 self.accumulator = 0.0;
335 }
336
337 pub fn debug_json(&self) -> String {
343 crate::debug::engine_json(
344 &self.world,
345 &self.map,
346 &self.nav,
347 &self.spatial,
348 &self.rng,
349 self.accumulator,
350 self.time_step,
351 )
352 .to_string()
353 }
354
355 pub fn serialize_state(&self) -> Result<Vec<u8>, String> {
361 let dump = EngineDump {
362 world: WorldDump {
363 gravity: [self.world.gravity.x, self.world.gravity.y],
364 integration_parameters: self.world.integration_parameters,
365 islands: self.world.islands.clone(),
366 broad_phase: self.world.broad_phase.clone(),
367 narrow_phase: self.world.narrow_phase.clone(),
368 bodies: self.world.bodies.clone(),
369 colliders: self.world.colliders.clone(),
370 impulse_joints: self.world.impulse_joints.clone(),
371 multibody_joints: self.world.multibody_joints.clone(),
372 },
373 map: &self.map,
374 rng: &self.rng,
375 accumulator: self.accumulator,
376 sim: self.sim.serialize(),
377 };
378
379 serde_json::to_vec(&dump).map_err(|e| e.to_string())
380 }
381
382 pub fn deserialize_state(&mut self, data: &[u8]) -> Result<(), String> {
385 let dump: EngineDumpOwned = serde_json::from_slice(data).map_err(|e| e.to_string())?;
386
387 let mut world = PhysicsWorld::new();
388
389 world.gravity = Vector::new(dump.world.gravity[0], dump.world.gravity[1]);
390 world.integration_parameters = dump.world.integration_parameters;
391 world.islands = dump.world.islands;
392 world.broad_phase = dump.world.broad_phase;
393 world.narrow_phase = dump.world.narrow_phase;
394 world.bodies = dump.world.bodies;
395 world.colliders = dump.world.colliders;
396 world.impulse_joints = dump.world.impulse_joints;
397 world.multibody_joints = dump.world.multibody_joints;
398
399 self.world = world;
400 self.map = dump.map;
401 self.rng = dump.rng;
402 self.accumulator = dump.accumulator;
403 self.sim.deserialize(dump.sim)?;
404
405 self.bodies_to_destroy.clear();
406 self.events.clear();
407
408 self.nav = self
411 .map
412 .as_ref()
413 .map(|map| NavigationSystem::generate(&map.grid, &map.physics_static, map.step));
414
415 self.sim.rebuild_spatial_grid(&self.world, &mut self.spatial);
416 self.sim.refresh_cached(&self.world);
417
418 Ok(())
419 }
420}
421
422#[derive(Serialize)]
423struct WorldDump {
424 gravity: [f32; 2],
425 integration_parameters: IntegrationParameters,
426 islands: IslandManager,
427 broad_phase: BroadPhaseBvh,
428 narrow_phase: NarrowPhase,
429 bodies: RigidBodySet,
430 colliders: ColliderSet,
431 impulse_joints: ImpulseJointSet,
432 multibody_joints: MultibodyJointSet,
433}
434
435#[derive(Deserialize)]
436struct WorldDumpOwned {
437 gravity: [f32; 2],
438 integration_parameters: IntegrationParameters,
439 islands: IslandManager,
440 broad_phase: BroadPhaseBvh,
441 narrow_phase: NarrowPhase,
442 bodies: RigidBodySet,
443 colliders: ColliderSet,
444 impulse_joints: ImpulseJointSet,
445 multibody_joints: MultibodyJointSet,
446}
447
448#[derive(Serialize)]
449struct EngineDump<'a> {
450 world: WorldDump,
451 map: &'a Option<GameMap>,
452 rng: &'a Rng,
453 accumulator: f32,
454 sim: serde_json::Value,
455}
456
457#[derive(Deserialize)]
458struct EngineDumpOwned {
459 world: WorldDumpOwned,
460 map: Option<GameMap>,
461 rng: Rng,
462 accumulator: f32,
463 sim: serde_json::Value,
464}
465
466#[cfg(test)]
473mod fixture {
474 use super::*;
475 use crate::config::FieldValue;
476 use serde::Deserialize;
477 use std::collections::{BTreeMap, BTreeSet};
478
479 #[derive(Deserialize)]
480 pub struct TestConfig {}
481
482 pub struct TestGame;
483
484 impl GameDef for TestGame {
485 type Config = TestConfig;
486 type Sim = TestSim;
487 }
488
489 #[derive(Clone, Copy)]
490 struct TestActor {
491 x: f32,
492 y: f32,
493 vx: f32,
494 vy: f32,
495 team: u8,
496 alive: bool,
497 }
498
499 pub struct TestSim {
500 actors: BTreeMap<u32, TestActor>,
501 scripted: BTreeSet<u32>,
502 }
503
504 impl GameSim<TestGame> for TestSim {
505 fn new(_cfg: &TestConfig, _engine_cfg: &EngineConfig) -> Self {
506 Self {
507 actors: BTreeMap::new(),
508 scripted: BTreeSet::new(),
509 }
510 }
511
512 fn spawn_actor(
513 &mut self,
514 _world: &mut PhysicsWorld,
515 _events: &mut Vec<CoreEvent>,
516 game_id: u32,
517 _model_name: &str,
518 team_id: u8,
519 x: f32,
520 y: f32,
521 _angle_deg: f32,
522 ) -> Result<(), String> {
523 self.actors.insert(
524 game_id,
525 TestActor { x, y, vx: 0.0, vy: 0.0, team: team_id, alive: true },
526 );
527
528 Ok(())
529 }
530
531 fn remove_actor(&mut self, _world: &mut PhysicsWorld, game_id: u32) {
532 self.actors.remove(&game_id);
533 self.scripted.remove(&game_id);
534 }
535
536 fn reset_actor(&mut self, _world: &mut PhysicsWorld, game_id: u32, team_id: u8, x: f32, y: f32, _angle_deg: f32) {
537 if let Some(actor) = self.actors.get_mut(&game_id) {
538 actor.x = x;
539 actor.y = y;
540 actor.team = team_id;
541 actor.alive = true;
542 }
543 }
544
545 fn reset_all_vitals(&mut self, _events: &mut Vec<CoreEvent>) {
546 for actor in self.actors.values_mut() {
547 actor.alive = true;
548 }
549 }
550
551 fn spawn_scripted_actor(
552 &mut self,
553 world: &mut PhysicsWorld,
554 _rng: &mut Rng,
555 events: &mut Vec<CoreEvent>,
556 game_id: u32,
557 model_name: &str,
558 team_id: u8,
559 x: f32,
560 y: f32,
561 angle_deg: f32,
562 ) -> Result<(), String> {
563 self.spawn_actor(world, events, game_id, model_name, team_id, x, y, angle_deg)?;
564 self.scripted.insert(game_id);
565
566 Ok(())
567 }
568
569 fn remove_scripted_actor(&mut self, world: &mut PhysicsWorld, game_id: u32) {
570 self.remove_actor(world, game_id);
571 }
572
573 fn apply_input(&mut self, game_id: u32, _seq: u32, action: &str, key_name: &str) {
574 let Some(actor) = self.actors.get_mut(&game_id) else {
575 return;
576 };
577
578 let magnitude = if action == "down" { 40.0 } else { 0.0 };
579
580 match key_name {
581 "forward" => actor.vy = -magnitude,
582 "back" => actor.vy = magnitude,
583 _ => {}
584 }
585 }
586
587 fn last_input_seq(&self, _game_id: u32) -> u32 {
588 0
589 }
590
591 fn is_alive(&self, game_id: u32) -> bool {
592 self.actors.get(&game_id).is_some_and(|a| a.alive)
593 }
594
595 fn actor_position(&self, _world: &PhysicsWorld, game_id: u32) -> Option<[f32; 2]> {
596 self.actors.get(&game_id).map(|a| [a.x, a.y])
597 }
598
599 fn prediction_state(&self, _world: &PhysicsWorld, game_id: u32) -> Option<([f32; PLAYER_STATE_LEN], bool)> {
600 self.actors
601 .get(&game_id)
602 .map(|a| ([a.x, a.y, 0.0, a.vx, a.vy, 0.0, 0.0, 0.0], false))
603 }
604
605 fn alive_players_flat(&self, _world: &PhysicsWorld) -> Vec<f32> {
606 self.actors
607 .iter()
608 .filter(|(_, a)| a.alive)
609 .flat_map(|(id, a)| [*id as f32, a.x, a.y])
610 .collect()
611 }
612
613 fn players_json(&self) -> String {
614 let rows: Vec<serde_json::Value> = self
615 .actors
616 .iter()
617 .map(|(id, a)| serde_json::json!({ "id": id, "x": a.x, "y": a.y, "team": a.team }))
618 .collect();
619
620 serde_json::to_string(&rows).unwrap()
621 }
622
623 fn on_fixed_step(&mut self, _ctx: &mut SimCtx, dt: f32) {
624 for actor in self.actors.values_mut() {
625 actor.x += actor.vx * dt;
626 actor.y += actor.vy * dt;
627 }
628 }
629
630 fn on_contacts(&mut self, _ctx: &mut SimCtx, _pairs: &[(ColliderHandle, ColliderHandle)]) {}
631
632 fn on_before_destroy(&mut self, _world: &PhysicsWorld, _handle: RigidBodyHandle) {}
633
634 fn on_ai_tick(&mut self, _ctx: &mut SimCtx, _dt: f32) {
635 for &id in &self.scripted {
637 if let Some(actor) = self.actors.get_mut(&id) {
638 actor.vx = 1.0;
639 }
640 }
641 }
642
643 fn refresh_cached(&mut self, _world: &PhysicsWorld) {}
644
645 fn build_snapshot_blocks(&mut self) -> (Vec<(String, Block)>, bool) {
646 let rows: Vec<(u8, Option<Vec<FieldValue>>)> = self
647 .actors
648 .iter()
649 .map(|(id, a)| (*id as u8, Some(vec![FieldValue::F32(a.x), FieldValue::F32(a.y)])))
650 .collect();
651
652 (vec![("actor".to_string(), Block::Indexed8(rows))], false)
653 }
654
655 fn remove_players_and_shots(&mut self, _world: &mut PhysicsWorld) -> Vec<String> {
656 let names: Vec<String> = self.actors.keys().map(|id| id.to_string()).collect();
657
658 self.actors.clear();
659 self.scripted.clear();
660
661 names
662 }
663
664 fn clear(&mut self) {
665 self.actors.clear();
666 self.scripted.clear();
667 }
668
669 fn serialize(&self) -> serde_json::Value {
670 let rows: Vec<serde_json::Value> = self
671 .actors
672 .iter()
673 .map(|(id, a)| serde_json::json!({ "id": id, "x": a.x, "y": a.y, "team": a.team }))
674 .collect();
675
676 serde_json::json!({ "actors": rows })
677 }
678
679 fn deserialize(&mut self, value: serde_json::Value) -> Result<(), String> {
680 let rows = value["actors"].as_array().ok_or("missing actors")?;
681
682 self.actors.clear();
683
684 for row in rows {
685 let id = row["id"].as_u64().ok_or("bad id")? as u32;
686 let x = row["x"].as_f64().ok_or("bad x")? as f32;
687 let y = row["y"].as_f64().ok_or("bad y")? as f32;
688 let team = row["team"].as_u64().ok_or("bad team")? as u8;
689
690 self.actors.insert(id, TestActor { x, y, vx: 0.0, vy: 0.0, team, alive: true });
691 }
692
693 Ok(())
694 }
695
696 fn rebuild_spatial_grid(&self, _world: &PhysicsWorld, _spatial: &mut SpatialGrid) {}
697 }
698}
699
700#[cfg(test)]
701mod tests {
702 use super::fixture::{TestConfig, TestGame};
703 use super::*;
704 use crate::snapshot::SnapshotPacker;
705
706 fn engine_config() -> EngineConfig {
707 serde_json::from_value(serde_json::json!({
708 "timeStep": 1.0 / 120.0,
709 "snapshot": {
710 "version": 3,
711 "port": 5,
712 "keys": {
713 "actor": { "id": 1, "kind": "indexed8", "class": "hot", "fields": [
714 { "name": "x", "ty": "f32", "interp": "lerp" },
715 { "name": "y", "ty": "f32", "interp": "lerp" }
716 ] }
717 }
718 },
719 "seed": 42
720 }))
721 .unwrap()
722 }
723
724 fn make_sim() -> EngineSim<TestGame> {
725 EngineSim::new(engine_config(), &TestConfig {})
726 }
727
728 #[test]
729 fn spawn_actor_and_fixed_step_moves_position() {
730 let mut sim = make_sim();
731
732 sim.spawn_actor(1, "m", 1, 0.0, 0.0, 0.0).unwrap();
733 sim.apply_input(1, 1, "down", "forward");
734
735 for _ in 0..60 {
736 sim.step(1.0 / 120.0);
737 }
738
739 let pos = sim.actor_position(1).unwrap();
740
741 assert!(pos[1] < 0.0); }
743
744 #[test]
745 fn remove_actor_clears_state() {
746 let mut sim = make_sim();
747
748 sim.spawn_actor(1, "m", 1, 5.0, 5.0, 0.0).unwrap();
749 assert!(sim.is_alive(1));
750
751 sim.remove_actor(1);
752 assert!(!sim.is_alive(1));
753 assert!(sim.actor_position(1).is_none());
754 }
755
756 #[test]
757 fn scripted_actor_runs_ai_tick() {
758 let mut sim = make_sim();
759
760 sim.spawn_scripted_actor(9, "m", 1, 0.0, 0.0, 0.0).unwrap();
761
762 sim.step(1.0 / 120.0);
765 sim.step(1.0 / 120.0);
766
767 let after = sim.actor_position(9).unwrap();
768
769 assert!(after[0] > 0.0); }
771
772 #[test]
773 fn build_snapshot_blocks_packs_through_generic_schema() {
774 let mut sim = make_sim();
775
776 sim.spawn_actor(1, "m", 1, 3.0, 4.0, 0.0).unwrap();
777 sim.spawn_actor(2, "m", 1, 7.0, 8.0, 0.0).unwrap();
778
779 let blocks = sim.build_snapshot_blocks();
780 let mut packer = SnapshotPacker::new(engine_config().snapshot);
781
782 assert!(packer.pack_body(&blocks).is_ok());
783 }
784
785 #[test]
786 fn clear_removes_all_actors() {
787 let mut sim = make_sim();
788
789 sim.spawn_actor(1, "m", 1, 0.0, 0.0, 0.0).unwrap();
790 sim.spawn_scripted_actor(2, "m", 1, 0.0, 0.0, 0.0).unwrap();
791
792 sim.clear();
793
794 assert!(!sim.is_alive(1));
795 assert!(!sim.is_alive(2));
796 assert_eq!(sim.alive_players_flat().len(), 0);
797 }
798
799 fn tiny_map_json() -> &'static str {
802 r#"{
803 "setId": "tiny",
804 "scale": 1,
805 "step": 10,
806 "map": [[1, 0], [0, 0]],
807 "physicsStatic": [1],
808 "respawns": { "team1": [[5, 5, 0]] }
809 }"#
810 }
811
812 #[test]
813 fn debug_json_dumps_world_map_and_rng() {
814 let mut sim = make_sim();
815
816 sim.load_map(tiny_map_json()).unwrap();
817
818 let dump: serde_json::Value = serde_json::from_str(&sim.debug_json()).unwrap();
819
820 let bodies = dump["bodies"].as_array().unwrap();
821 let colliders = dump["colliders"].as_array().unwrap();
822
823 assert_eq!(bodies.len(), 1);
824 assert_eq!(colliders.len(), 1);
825 assert_eq!(bodies[0]["bodyType"], "Fixed");
826 assert_eq!(bodies[0]["translation"], serde_json::json!([5.0, 5.0]));
827 assert_eq!(colliders[0]["shape"], "cuboid");
828 assert_eq!(colliders[0]["halfExtents"], serde_json::json!([5.0, 5.0]));
829 assert_eq!(colliders[0]["isSensor"], false);
830 assert_eq!(colliders[0]["parent"], bodies[0]["handle"]);
831
832 assert_eq!(dump["map"]["setId"], "tiny");
833 assert_eq!(dump["map"]["staticBodies"], 1);
834 assert_eq!(dump["map"]["grid"]["rows"], 2);
835 assert_eq!(dump["map"]["respawns"]["team1"], 1);
836
837 assert!(dump["nav"]["nodes"].as_u64().unwrap() > 0);
838 assert_eq!(dump["spatial"]["cells"], 0);
839 assert_eq!(dump["rng"]["state"], "42");
840 assert_eq!(dump["step"]["accumulator"], 0.0);
841 }
842
843 #[test]
844 fn debug_json_is_null_for_map_and_nav_without_map() {
845 let dump: serde_json::Value = serde_json::from_str(&make_sim().debug_json()).unwrap();
846
847 assert!(dump["map"].is_null());
848 assert!(dump["nav"].is_null());
849 assert_eq!(dump["bodies"].as_array().unwrap().len(), 0);
850 }
851
852 #[test]
853 fn debug_json_is_stable_between_identical_runs() {
854 let mut a = make_sim();
855 let mut b = make_sim();
856
857 for sim in [&mut a, &mut b] {
858 sim.load_map(tiny_map_json()).unwrap();
859 sim.spawn_actor(1, "m", 1, 3.0, 4.0, 0.0).unwrap();
860 sim.step(1.0 / 120.0);
861 }
862
863 assert_eq!(a.debug_json(), b.debug_json());
864 }
865
866 #[test]
867 fn serialize_deserialize_round_trips_actors() {
868 let mut sim = make_sim();
869
870 sim.spawn_actor(1, "m", 3, 11.0, 22.0, 0.0).unwrap();
871
872 let dump = sim.sim.serialize();
873 let mut restored = make_sim();
874
875 restored.sim.deserialize(dump).unwrap();
876
877 assert_eq!(restored.actor_position(1), Some([11.0, 22.0]));
878 }
879}