rusting_engine 1.4.0

Vulkan 3D game engine with GPU-accelerated physics for massive physics-heavy scenes
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! ECS application runtime and canonical scene components.
//!
//! This module is deliberately independent of Vulkan. Rendering and editor
//! integrations consume the ECS state through the `RenderExtract` schedule.

mod actions;
mod click;
mod components;
mod cpu_physics;
mod determinism;
mod events;
mod game_feel;
pub(crate) mod hierarchy;
mod hybrid_physics;
mod input;
mod physics_benchmark;
pub mod picking;
mod player;
mod render_benchmark;
mod render_world;
mod replay;
mod scene_file;
pub mod sim_math;
mod snapshot;
mod state_hash;
#[cfg(test)]
mod tests;
mod time;
mod two_d;
#[cfg(feature = "ui")]
mod ui;

pub use actions::{ActionMap, InputBinding};
pub use components::*;
pub(crate) use cpu_physics::gpu_shape_words;
pub use cpu_physics::{
    CharacterMove, CollisionEvent, Contact, GpuCollider, PhysicsWorld, RayHit,
    Sleeping, SLEEP_STEPS,
};
pub use determinism::*;
pub use events::EventQueue;
pub use game_feel::*;
pub use hierarchy::{propagate_transforms, HierarchyDiagnostics};
pub use hybrid_physics::*;
pub use input::{KeyCode, MouseButton, RuntimeInput};
pub use physics_benchmark::{
    BenchmarkBody, PhysicsBenchmark, BENCHMARK_TOWER_HEIGHT,
};
pub use player::*;
pub use render_benchmark::*;
pub use render_world::*;
pub use replay::*;
pub use rusting_core::app::AppError;
pub use rusting_core::input::ClickEvent;
pub use rusting_core::schedule::{CpuFrameTimings, FrameReport, ScheduleStage};
pub use scene_file::*;
pub use snapshot::{SnapshotError, WorldSnapshot};
pub use state_hash::*;
pub use time::{FrameTime, RandomSeed, TimeControl};
pub use two_d::*;
#[cfg(feature = "ui")]
pub use ui::RuntimeUi;

use std::hash::Hasher;
use std::time::{Duration, Instant};

use bevy_ecs::bundle::Bundle;
use bevy_ecs::entity::Entity;
use bevy_ecs::prelude::{IntoScheduleConfigs, Resource, Schedule, World};
use bevy_ecs::system::ScheduleSystem;

/// Small non-cryptographic hasher for per-frame ECS change fingerprints.
/// Stable handles and float bits do not need the cost of a DOS-resistant map
/// hasher; this value is only used to decide whether cached data needs a check.
pub(super) struct FastHasher(u64);

impl Default for FastHasher {
    fn default() -> Self {
        Self(0xcbf2_9ce4_8422_2325)
    }
}

impl Hasher for FastHasher {
    fn finish(&self) -> u64 {
        self.0
    }

    fn write(&mut self, bytes: &[u8]) {
        for byte in bytes {
            self.0 ^= u64::from(*byte);
            self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3);
        }
    }

    fn write_u8(&mut self, value: u8) {
        self.write_u64(u64::from(value));
    }

    fn write_u32(&mut self, value: u32) {
        self.write_u64(u64::from(value));
    }

    fn write_u64(&mut self, value: u64) {
        self.0 ^= value;
        self.0 = self.0.wrapping_mul(0x0000_0100_0000_01b3);
    }
}

/// A reusable unit of runtime configuration.
pub trait Plugin: Send + Sync + 'static {
    fn build(&self, app: &mut App) -> Result<(), AppError>;

    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }
}

#[derive(Resource, Clone, Default)]
struct ExitState {
    requested: bool,
}

/// Owns the canonical ECS world and all engine schedules.
pub struct App {
    world: World,
    startup: Schedule,
    fixed_update: Schedule,
    update: Schedule,
    post_update: Schedule,
    render_extract: Schedule,
    startup_complete: bool,
    event_maintenance: Vec<fn(&mut World)>,
    plugins: Vec<&'static str>,
    replay_recorder: Option<ReplayRecorder>,
    snapshot_types: snapshot::SnapshotTypes,
}

impl Default for App {
    fn default() -> Self {
        let mut world = World::new();
        world.insert_resource(FrameTime::default());
        world.insert_resource(TimeControl::default());
        world.insert_resource(RandomSeed::default());
        world.insert_resource(ExitState::default());
        world.insert_resource(HierarchyDiagnostics::default());
        world.insert_resource(RenderSettings::default());
        world.insert_resource(PhysicsSettings::default());
        world.insert_resource(PhysicsBackendStatus {
            gameplay_available: true,
            ..PhysicsBackendStatus::default()
        });
        world.init_resource::<PhysicsWorld>();
        world.insert_resource(SceneComponentRegistry::default());
        world.init_resource::<CpuFrameTimings>();
        // Bevy adds this on the first schedule run. Adding it here keeps its
        // entity id the same before and after, which snapshots rely on.
        world.init_resource::<bevy_ecs::schedule::Schedules>();
        input::install(&mut world);
        actions::install(&mut world);
        player::bind_default_actions(&mut world.resource_mut::<ActionMap>());
        #[cfg(feature = "ui")]
        world.init_resource::<RuntimeUi>();

        // Systems a game adds to FixedUpdate without an order still run in
        // one order every tick: the single-threaded executor follows the
        // build's topological sort instead of thread timing.
        // ponytail: gives up parallel fixed-step systems; order them
        // explicitly and switch back if a game needs the threads.
        let mut fixed_update = Schedule::default();
        fixed_update
            .set_executor(bevy_ecs::schedule::SingleThreadedExecutor::new());
        let mut post_update = Schedule::default();
        post_update.add_systems(propagate_transforms);

        let mut app = Self {
            world,
            startup: Schedule::default(),
            fixed_update,
            update: Schedule::default(),
            post_update,
            render_extract: Schedule::default(),
            startup_complete: false,
            event_maintenance: Vec::new(),
            plugins: Vec::new(),
            replay_recorder: None,
            snapshot_types: snapshot::SnapshotTypes::default(),
        };
        snapshot::register_engine_types(&mut app.snapshot_types);
        app.add_event::<ClickEvent>();
        app.add_system(ScheduleStage::Update, click::route_click_events);
        app.add_event::<CollisionEvent>();
        // One chain: these systems all write `Transform`, and unordered
        // systems would run in whatever order threads finish.
        app.add_systems(
            ScheduleStage::FixedUpdate,
            (
                cpu_physics::step_cpu_physics,
                player::player_move,
                two_d::platformer_move,
                game_feel::trigger_on_contact,
                game_feel::collect_pickups,
                game_feel::fire_sound_cues,
                // Existing particles move before new ones spawn at rest.
                game_feel::update_burst_particles,
                game_feel::fire_bursts,
                game_feel::advance_tweens,
            )
                .chain(),
        );
        app.add_system(ScheduleStage::Update, player::player_look);
        app.add_event::<SoundEvent>();
        app.add_event::<HudButtonPressed>();
        #[cfg(feature = "ui")]
        app.add_system(ScheduleStage::Update, game_feel::draw_hud);
        app.add_system(ScheduleStage::Update, two_d::build_tile_maps);
        app.add_system(
            ScheduleStage::Update,
            game_feel::apply_scene_background,
        );
        app.add_system(ScheduleStage::Update, two_d::platformer_jump);
        app
    }
}

impl App {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn world(&self) -> &World {
        &self.world
    }

    pub fn world_mut(&mut self) -> &mut World {
        &mut self.world
    }

    pub fn insert_resource<R: Resource>(&mut self, resource: R) -> &mut Self {
        self.world.insert_resource(resource);
        self
    }

    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> Entity {
        let mut entity = self.world.spawn(bundle);
        if !entity.contains::<SceneId>() {
            entity.insert(SceneId::new());
        }
        entity.id()
    }

    /// Allows a game plugin to persist one of its compiled Rust components in
    /// scene files. Describe the type with [`reflect!`](crate::reflect!)
    /// first; the description drives saving, the Inspector, and field paths.
    /// Registration does not add scripting or dynamic dispatch to normal ECS
    /// queries.
    pub fn register_scene_component<T>(
        &mut self,
        name: impl Into<String>,
    ) -> Result<&mut Self, SceneIoError>
    where
        T: bevy_ecs::component::Component
            + serde::Serialize
            + serde::de::DeserializeOwned
            + Default
            + crate::reflect::Reflect,
    {
        self.world
            .resource_mut::<SceneComponentRegistry>()
            .register::<T>(name)?;
        Ok(self)
    }

    /// Records a renamed or removed field of a registered component, so
    /// scenes saved before the change still load. See
    /// [`SceneComponentRegistry::add_migration`].
    pub fn migrate_scene_component(
        &mut self,
        name: &str,
        migration: crate::reflect::FieldMigration,
    ) -> Result<&mut Self, SceneIoError> {
        self.world
            .resource_mut::<SceneComponentRegistry>()
            .add_migration(name, migration)?;
        Ok(self)
    }

    pub fn despawn(&mut self, entity: Entity) -> Result<(), AppError> {
        if self.world.despawn(entity) {
            Ok(())
        } else {
            Err(AppError::MissingEntity(entity))
        }
    }

    pub fn add_systems<M>(
        &mut self,
        stage: ScheduleStage,
        systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
    ) -> &mut Self {
        self.schedule_mut(stage).add_systems(systems);
        self
    }

    pub fn add_system<M>(
        &mut self,
        stage: ScheduleStage,
        system: impl IntoScheduleConfigs<ScheduleSystem, M>,
    ) -> &mut Self {
        self.add_systems(stage, system)
    }

    pub fn add_plugin<P: Plugin>(
        &mut self,
        plugin: P,
    ) -> Result<&mut Self, AppError> {
        let name = plugin.name();
        if self.plugins.contains(&name) {
            return Err(AppError::DuplicatePlugin(name));
        }
        plugin.build(self)?;
        self.plugins.push(name);
        Ok(self)
    }

    pub fn add_event<T: Send + Sync + 'static>(&mut self) -> &mut Self {
        if !self.world.contains_resource::<EventQueue<T>>() {
            self.world.insert_resource(EventQueue::<T>::default());
            self.event_maintenance.push(events::begin_frame::<T>);
        }
        self
    }

    pub fn send_event<T: Send + Sync + 'static>(&mut self, event: T) {
        let mut events = self
            .world
            .get_resource_mut::<EventQueue<T>>()
            .unwrap_or_else(|| {
                panic!(
                    "event `{}` was not registered",
                    std::any::type_name::<T>()
                )
            });
        events.send(event);
    }

    pub fn request_exit(&mut self) {
        self.world.resource_mut::<ExitState>().requested = true;
    }

    #[must_use]
    pub fn exit_requested(&self) -> bool {
        self.world.resource::<ExitState>().requested
    }

    pub fn set_parent(
        &mut self,
        child: Entity,
        parent: Entity,
    ) -> Result<(), AppError> {
        hierarchy::set_parent(&mut self.world, child, parent)
    }

    pub fn clear_parent(&mut self, child: Entity) -> Result<(), AppError> {
        hierarchy::clear_parent(&mut self.world, child)
    }

    /// Records every following [`App::update`] into a [`Replay`]. The
    /// recorder lives outside the `World`: in bevy 0.19 a resource is an
    /// entity, and inserting one would shift the ids of later entities.
    pub fn start_recording(&mut self) {
        self.replay_recorder = Some(ReplayRecorder::new(&self.world));
    }

    /// Stops recording and returns the replay, or `None` when not recording.
    pub fn finish_recording(&mut self) -> Option<Replay> {
        self.replay_recorder.take().map(ReplayRecorder::finish)
    }

    /// Lets [`App::snapshot`] copy component or resource `T` (in bevy 0.19
    /// a resource is a component on its own entity). Every type in the
    /// world needs this or [`App::ignore_in_snapshots`].
    pub fn register_snapshot_component<T>(&mut self) -> &mut Self
    where
        T: bevy_ecs::component::Component<
                Mutability = bevy_ecs::component::Mutable,
            > + Clone,
    {
        self.snapshot_types.register::<T>();
        self
    }

    /// Leaves `T` out of snapshots: a restore keeps the value the app
    /// already has. For caches, handles to external state, and values fixed
    /// after setup.
    pub fn ignore_in_snapshots<T: 'static>(&mut self) -> &mut Self {
        self.snapshot_types.ignore::<T>();
        self
    }

    /// Copies the whole world between frames; see [`WorldSnapshot`].
    pub fn snapshot(&mut self) -> Result<WorldSnapshot, SnapshotError> {
        let entities =
            snapshot::capture_world(&mut self.world, &self.snapshot_types)?;
        let allocator = snapshot::read_allocator(&mut self.world);
        snapshot::write_allocator(&mut self.world, &allocator);
        Ok(WorldSnapshot {
            tick: self.world.resource::<FrameTime>().fixed_tick,
            startup_complete: self.startup_complete,
            entities,
            allocator,
        })
    }

    /// Puts the world back to `snapshot`. The app must be built the same
    /// way as the one snapshotted (same plugins and scene) and not be past
    /// the snapshot; a new app from the same setup always works. On error
    /// the app is left half restored; build a new one.
    pub fn restore(
        &mut self,
        snapshot: &WorldSnapshot,
    ) -> Result<(), SnapshotError> {
        snapshot::restore_world(&mut self.world, snapshot)?;
        self.startup_complete = snapshot.startup_complete;
        Ok(())
    }

    /// Advances every schedule once using a caller-provided real-frame delta.
    pub fn update(
        &mut self,
        real_delta: Duration,
    ) -> Result<FrameReport, AppError> {
        if !self.startup_complete {
            self.startup.run(&mut self.world);
            self.startup_complete = true;
        }

        for maintain in &self.event_maintenance {
            maintain(&mut self.world);
        }

        if let Some(recorder) = &mut self.replay_recorder {
            recorder.frame_start(&self.world, real_delta);
        }
        let fixed_steps = time::advance(&mut self.world, real_delta)?;
        let start = Instant::now();
        // `advance` counts the frame's steps at once; each step sees the
        // ticks completed before it, so tick-indexed values differ per tick.
        let end_tick = self.world.resource::<FrameTime>().fixed_tick;
        let first_tick = end_tick.saturating_sub(u64::from(fixed_steps));
        for step in 0..u64::from(fixed_steps) {
            self.world.resource_mut::<FrameTime>().fixed_tick =
                first_tick + step;
            self.fixed_update.run(&mut self.world);
            hybrid_physics::stamp_gpu_commands(&mut self.world);
            state_hash::record_state_hash(&mut self.world);
        }
        self.world.resource_mut::<FrameTime>().fixed_tick = end_tick;
        if let Some(recorder) = &mut self.replay_recorder {
            recorder.frame_hashes(&self.world, fixed_steps);
        }
        let physics = start.elapsed();
        #[cfg(feature = "ui")]
        if let Some(mut ui) = self.world.get_resource_mut::<RuntimeUi>() {
            ui.begin_pass();
        }
        self.update.run(&mut self.world);
        self.post_update.run(&mut self.world);
        #[cfg(feature = "ui")]
        if let Some(mut ui) = self.world.get_resource_mut::<RuntimeUi>() {
            ui.end_pass();
        }
        let start = Instant::now();
        self.render_extract.run(&mut self.world);
        let extraction = start.elapsed();
        if let Some(mut timings) =
            self.world.get_resource_mut::<CpuFrameTimings>()
        {
            timings.physics = physics;
            timings.extraction = extraction;
        }

        Ok(FrameReport {
            fixed_steps,
            exit_requested: self.exit_requested(),
        })
    }

    /// Runs a simple main-thread loop until [`App::request_exit`] is called.
    pub fn run(mut self) -> Result<(), AppError> {
        let mut previous = Instant::now();
        while !self.exit_requested() {
            let now = Instant::now();
            self.update(now.saturating_duration_since(previous))?;
            previous = now;
            std::thread::yield_now();
        }
        Ok(())
    }

    fn schedule_mut(&mut self, stage: ScheduleStage) -> &mut Schedule {
        match stage {
            ScheduleStage::Startup => &mut self.startup,
            ScheduleStage::FixedUpdate => &mut self.fixed_update,
            ScheduleStage::Update => &mut self.update,
            ScheduleStage::PostUpdate => &mut self.post_update,
            ScheduleStage::RenderExtract => &mut self.render_extract,
        }
    }
}

/// Fallible builder for the ECS runtime.
pub struct EngineBuilder {
    fixed_delta: Duration,
    max_fixed_steps: u32,
    plugins: Vec<Box<dyn Plugin>>,
}

impl Default for EngineBuilder {
    fn default() -> Self {
        Self {
            fixed_delta: Duration::from_secs_f64(1.0 / 60.0),
            max_fixed_steps: 8,
            plugins: Vec::new(),
        }
    }
}

impl EngineBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn fixed_delta(mut self, fixed_delta: Duration) -> Self {
        self.fixed_delta = fixed_delta;
        self
    }

    #[must_use]
    pub fn max_fixed_steps(mut self, max_fixed_steps: u32) -> Self {
        self.max_fixed_steps = max_fixed_steps.max(1);
        self
    }

    #[must_use]
    pub fn plugin<P: Plugin>(mut self, plugin: P) -> Self {
        self.plugins.push(Box::new(plugin));
        self
    }

    pub fn build(self) -> Result<App, AppError> {
        if self.fixed_delta.is_zero() {
            return Err(AppError::InvalidFixedDelta);
        }
        let mut app = App::new();
        {
            let mut control = app.world.resource_mut::<TimeControl>();
            control.fixed_delta = self.fixed_delta;
            control.max_fixed_steps = self.max_fixed_steps;
        }
        for plugin in self.plugins {
            let name = plugin.name();
            if app.plugins.contains(&name) {
                return Err(AppError::DuplicatePlugin(name));
            }
            plugin.build(&mut app)?;
            app.plugins.push(name);
        }
        Ok(app)
    }
}