archetype_ecs 1.2.0

Archetype ECS - High-performance Entity Component System with parallel execution
Documentation
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Phase 4 Executor, Sync, and Debugging
//! Combined to fit size constraints

// ============================================================================
// executor.rs
// ============================================================================

use crate::error::{EcsError, Result};
use crate::schedule::Schedule;
use crate::system::{System, SystemId};
use crate::World;
use rustc_hash::FxHashMap;
use std::time::{Duration, Instant};

#[cfg(feature = "profiling")]
use tracing::info_span;

/// System execution profiler
#[derive(Debug, Clone)]
pub struct SystemStats {
    pub min: Duration,
    pub max: Duration,
    pub avg: Duration,
    pub call_count: u64,
}

/// System profiler for collecting timing data
pub struct SystemProfiler {
    timings: FxHashMap<SystemId, Vec<Duration>>,
    call_counts: FxHashMap<SystemId, u64>,
}

impl SystemProfiler {
    pub fn new() -> Self {
        Self {
            timings: FxHashMap::default(),
            call_counts: FxHashMap::default(),
        }
    }

    pub fn record_execution(&mut self, id: SystemId, duration: Duration) {
        self.timings.entry(id).or_default().push(duration);
        self.call_counts
            .entry(id)
            .and_modify(|c| *c += 1)
            .or_insert(1);
    }

    pub fn get_stats(&self, id: SystemId) -> Option<SystemStats> {
        let timings = self.timings.get(&id)?;
        if timings.is_empty() {
            return None;
        }

        let min = *timings.iter().min().unwrap_or(&Duration::ZERO);
        let max = *timings.iter().max().unwrap_or(&Duration::ZERO);
        let avg = timings.iter().sum::<Duration>() / timings.len() as u32;

        Some(SystemStats {
            min,
            max,
            avg,
            call_count: *self.call_counts.get(&id).unwrap_or(&0),
        })
    }

    pub fn clear(&mut self) {
        self.timings.clear();
        self.call_counts.clear();
    }
}

impl Default for SystemProfiler {
    fn default() -> Self {
        Self::new()
    }
}

/// Per-system timing data for a single frame
#[derive(Debug, Clone)]
pub struct SystemTiming {
    pub name: String,
    pub duration: Duration,
}

/// Execution profile for a frame
#[derive(Debug, Clone)]
pub struct ExecutionProfile {
    pub total_frame_time: Duration,
    pub system_timings: Vec<SystemTiming>,
}

/// Enhanced profiling statistics
#[derive(Debug, Clone)]
pub struct ProfilingStats {
    pub total_frame_time: Duration,
    pub system_timings: Vec<SystemTiming>,
    pub time_per_entity: f32,
    pub memory_usage: usize,
    pub entity_count: usize,
    pub systems_per_second: f32,
}

impl Default for ProfilingStats {
    fn default() -> Self {
        Self {
            total_frame_time: Duration::ZERO,
            system_timings: Vec::new(),
            time_per_entity: 0.0,
            memory_usage: 0,
            entity_count: 0,
            systems_per_second: 0.0,
        }
    }
}

/// Frame executor
pub struct Executor<'s> {
    schedule: &'s mut Schedule,
    pub profiler: SystemProfiler,
    pub last_profile: Option<ExecutionProfile>,
}

impl<'s> Executor<'s> {
    /// Create new executor with schedule reference
    pub fn new(schedule: &'s mut Schedule) -> Self {
        Self {
            schedule,
            profiler: SystemProfiler::new(),
            last_profile: None,
        }
    }

    /// Execute one frame
    pub fn execute_frame(&mut self, world: &mut World) -> Result<()> {
        world.increment_tick();

        self.schedule.ensure_built()?;

        // Check if we have named stages with dependencies (not default stages)
        let has_named_stages = self.schedule.stages.iter().any(|s| s.name != "default");

        if has_named_stages {
            let frame_start = Instant::now();
            let mut system_timings = Vec::with_capacity(self.schedule.systems.len());
            let mut commands = CommandBuffer::new();
            let parallel_plan = self.schedule.parallel_plan.clone();

            for stage_plan in parallel_plan {
                for group in stage_plan.parallel_groups {
                    for &system_id_idx in &group.system_indices {
                        let system_id = SystemId(system_id_idx as u32);
                        let system = self
                            .schedule
                            .system_mut_by_id(system_id)
                            .ok_or(EcsError::SystemNotFound)?;
                        let system_name = system.name();

                        let start = Instant::now();
                        system.run(world, &mut commands)?;
                        let duration = start.elapsed();

                        self.profiler.record_execution(system_id, duration);
                        system_timings.push(SystemTiming {
                            name: system_name.to_string(),
                            duration,
                        });
                    }
                }
                // Flush commands after each stage
                commands.apply(world)?;
            }

            let frame_duration = frame_start.elapsed();
            self.last_profile = Some(ExecutionProfile {
                total_frame_time: frame_duration,
                system_timings,
            });
        } else {
            // Use the stage plan for backward compatibility
            let stage_plan: Vec<Vec<SystemId>> = self
                .schedule
                .stage_plan()
                .iter()
                .map(|stage| stage.to_vec())
                .collect();
            let frame_start = Instant::now();
            let mut system_timings = Vec::with_capacity(self.schedule.systems.len());
            let mut commands = CommandBuffer::new();

            for stage in stage_plan {
                for system_id in stage {
                    let system = self
                        .schedule
                        .system_mut_by_id(system_id)
                        .ok_or(EcsError::SystemNotFound)?;
                    let system_name = system.name();

                    let start = Instant::now();
                    system.run(world, &mut commands)?;
                    let duration = start.elapsed();

                    self.profiler.record_execution(system_id, duration);
                    system_timings.push(SystemTiming {
                        name: system_name.to_string(),
                        duration,
                    });
                }
                commands.apply(world)?;
            }

            let frame_duration = frame_start.elapsed();
            self.last_profile = Some(ExecutionProfile {
                total_frame_time: frame_duration,
                system_timings,
            });
        }

        Ok(())
    }

    /// Execute systems in parallel where possible
    ///
    /// Uses the dependency graph to determine which systems can run concurrently.
    /// See `ParallelExecutor::execute_stage` for detailed safety documentation.
    pub fn execute_frame_parallel(&mut self, world: &mut World) -> Result<()> {
        world.increment_tick();
        self.schedule.ensure_built()?;

        let systems_ptr = self.schedule.systems.as_mut_ptr() as usize;
        let systems_len = self.schedule.systems.len();
        let parallel_plan = self.schedule.parallel_plan.clone();

        for stage_plan in parallel_plan {
            #[cfg(feature = "profiling")]
            let _stage_span = info_span!("stage", name = %stage_plan.name).entered();

            for group in stage_plan.parallel_groups {
                use rayon::prelude::*;

                // SAFETY: We use UnsafeWorldCell to provide disjoint access to threads.
                // The scheduler (via DependencyGraph) guarantees that systems in the same
                // group do not have conflicting component accesses.
                let world_cell = unsafe { world.as_unsafe_world_cell() };

                let results: Vec<(Result<()>, CommandBuffer)> = group
                    .system_indices
                    .par_iter()
                    .map(move |&sys_idx| {
                        let mut commands = CommandBuffer::new();
                        if sys_idx >= systems_len {
                            return (Err(EcsError::SystemNotFound), commands);
                        }

                        // SAFETY:
                        // 1. sys_idx is valid.
                        // 2. Systems in the same group have been proven non-conflicting by the scheduler.
                        // 3. Each thread handles a unique sys_idx.
                        let system =
                            unsafe { &mut *(systems_ptr as *mut Box<dyn System>).add(sys_idx) };
                        let res = unsafe { system.run_parallel(world_cell, &mut commands) };
                        (res, commands)
                    })
                    .collect();

                // Check for errors and collect commands
                for (result, mut commands) in results {
                    result?;
                    commands.apply(world)?;
                }

                // Sync point after each parallel group
                self.barrier(world)?;
            }
        }

        Ok(())
    }

    /// Execute with automatic parallel detection
    pub fn execute_frame_auto(&mut self, world: &mut World) -> Result<()> {
        // Use parallel if multiple systems, sequential if one
        if self.schedule.systems.len() > 1 {
            self.execute_frame_parallel(world)
        } else {
            self.execute_frame(world)
        }
    }

    /// Execute systems and process observer events
    pub fn execute_frame_with_events(&mut self, world: &mut World) -> Result<()> {
        let mut commands = CommandBuffer::new();
        // Execute systems
        for system in &mut self.schedule.systems {
            system.run(world, &mut commands)?;
        }
        commands.apply(world)?;

        // Process queued events
        world.process_events()?;

        Ok(())
    }

    /// Execute with events and profiling
    pub fn execute_frame_full(&mut self, world: &mut World) -> Result<()> {
        #[cfg(feature = "profiling")]
        let _span = info_span!("execute_frame_full");

        let mut commands = CommandBuffer::new();
        // Execute systems
        for system in &mut self.schedule.systems {
            system.run(world, &mut commands)?;
        }
        commands.apply(world)?;

        // Process all events
        world.process_events()?;

        Ok(())
    }

    /// Execute with hierarchy system
    pub fn execute_with_hierarchy(&mut self, world: &mut World) -> Result<()> {
        use crate::hierarchy_system::HierarchyUpdateSystem;

        let mut commands = CommandBuffer::new();
        // Run hierarchy update first (transforms)
        let mut hierarchy_system = HierarchyUpdateSystem::new();
        hierarchy_system.run(world, &mut commands)?;

        // Then run user systems
        for system in &mut self.schedule.systems {
            system.run(world, &mut commands)?;
        }
        commands.apply(world)?;

        // Process events if Phase 3 is enabled
        world.process_events()?;

        Ok(())
    }

    /// Execute with everything (hierarchy + systems + events)
    pub fn execute_full(&mut self, world: &mut World) -> Result<()> {
        use crate::hierarchy_system::HierarchyUpdateSystem;

        let mut commands = CommandBuffer::new();
        // Execute hierarchy system
        let mut hierarchy_system = HierarchyUpdateSystem::new();
        hierarchy_system.run(world, &mut commands)?;

        // Execute user systems
        for system in &mut self.schedule.systems {
            system.run(world, &mut commands)?;
        }
        commands.apply(world)?;

        // Process events
        world.process_events()?;

        Ok(())
    }

    /// Execute with global event processing (Phase 6)
    pub fn execute_with_global_events(&mut self, world: &mut World) -> Result<()> {
        let mut commands = CommandBuffer::new();
        // Execute systems
        for system in &mut self.schedule.systems {
            system.run(world, &mut commands)?;
        }
        commands.apply(world)?;

        // Process global events published by systems
        world.process_global_events()?;

        Ok(())
    }

    /// Execute complete frame (hierarchy + systems + global events + entity events)
    pub fn execute_complete_frame(&mut self, world: &mut World) -> Result<()> {
        use crate::hierarchy_system::HierarchyUpdateSystem;

        let mut commands = CommandBuffer::new();
        // 1. Update hierarchy transforms
        let mut hierarchy_system = HierarchyUpdateSystem::new();
        hierarchy_system.run(world, &mut commands)?;

        // 2. Execute systems
        for system in &mut self.schedule.systems {
            system.run(world, &mut commands)?;
        }
        commands.apply(world)?;

        // 3. Process global events (Phase 6)
        world.process_global_events()?;

        // 4. Process entity lifecycle events (Phase 3)
        world.process_events()?;

        Ok(())
    }

    fn barrier(&mut self, _world: &mut World) -> Result<()> {
        // Flush command buffers
        // Compact archetypes (optional)
        Ok(())
    }

    /// Get the most recent execution profile
    pub fn profile(&self) -> Option<&ExecutionProfile> {
        self.last_profile.as_ref()
    }

    /// Print profiling information for the last frame
    pub fn print_profile(&self) {
        if let Some(profile) = &self.last_profile {
            println!(
                "Frame time: {:.3?} ({} systems)",
                profile.total_frame_time,
                profile.system_timings.len()
            );
            for (index, timing) in profile.system_timings.iter().enumerate() {
                println!("  {:02}: {:<24} {:?}", index, timing.name, timing.duration);
            }
        } else {
            println!("No profiling data collected yet.");
        }
    }

    /// Get detailed profiling stats
    pub fn profiling_stats(&self, world: &World) -> ProfilingStats {
        let mut stats = ProfilingStats::default();

        if let Some(profile) = &self.last_profile {
            stats.total_frame_time = profile.total_frame_time;
            stats.system_timings = profile.system_timings.clone();

            // Calculate per-entity timing
            stats.entity_count = world.entity_count() as usize;
            if stats.entity_count > 0 {
                stats.time_per_entity =
                    stats.total_frame_time.as_secs_f32() / stats.entity_count as f32;
            }

            // Calculate systems per second
            if !stats.total_frame_time.is_zero() {
                stats.systems_per_second =
                    stats.system_timings.len() as f32 / stats.total_frame_time.as_secs_f32();
            }

            // Get memory usage
            stats.memory_usage = world.memory_stats().total_memory;
        }

        stats
    }

    /// Export profiling data to CSV
    pub fn export_profiling_csv(&self, world: &World, path: &str) -> Result<()> {
        use std::fs::File;
        use std::io::Write;

        if let Some(profile) = &self.last_profile {
            let mut file = File::create(path)?;

            // Write CSV header
            writeln!(file, "system_name,duration_ms,duration_us,percentage")?;

            // Write system timings
            for timing in &profile.system_timings {
                let duration_ms = timing.duration.as_millis();
                let duration_us = timing.duration.as_micros();
                let percentage = (timing.duration.as_secs_f32()
                    / profile.total_frame_time.as_secs_f32())
                    * 100.0;

                writeln!(
                    file,
                    "{},{},{},{:.2}",
                    timing.name, duration_ms, duration_us, percentage
                )?;
            }

            // Write summary
            writeln!(file)?;
            writeln!(
                file,
                "Total Frame Time,{} ms",
                profile.total_frame_time.as_millis()
            )?;
            writeln!(file, "Entity Count,{}", world.entity_count())?;
            writeln!(
                file,
                "Time Per Entity,{:.6} ms",
                (profile.total_frame_time.as_secs_f32() / world.entity_count() as f32) * 1000.0
            )?;
            writeln!(
                file,
                "Memory Usage,{} bytes",
                world.memory_stats().total_memory
            )?;
        }

        Ok(())
    }

    /// Print enhanced profiling summary
    pub fn print_profiling_summary(&self, world: &World) {
        let stats = self.profiling_stats(world);

        println!("=== Enhanced Profiling Summary ===");
        println!(
            "Frame Time: {:.3?} ({:.1} FPS)",
            stats.total_frame_time,
            1.0 / stats.total_frame_time.as_secs_f32()
        );
        println!(
            "Systems: {} ({:.1} systems/sec)",
            stats.system_timings.len(),
            stats.systems_per_second
        );
        println!("Entities: {}", stats.entity_count);
        println!("Time/Entity: {:.6} ms", stats.time_per_entity * 1000.0);
        println!(
            "Memory: {} bytes ({:.1} MB)",
            stats.memory_usage,
            stats.memory_usage as f64 / 1_048_576.0
        );

        // Show slowest systems
        if !stats.system_timings.is_empty() {
            println!("\nSlowest Systems:");
            let mut sorted_timings = stats.system_timings.clone();
            sorted_timings.sort_by(|a, b| b.duration.cmp(&a.duration));

            for (i, timing) in sorted_timings.iter().take(5).enumerate() {
                let percentage =
                    (timing.duration.as_secs_f32() / stats.total_frame_time.as_secs_f32()) * 100.0;
                println!(
                    "  {}. {} - {:.3?} ({:.1}%)",
                    i + 1,
                    timing.name,
                    timing.duration,
                    percentage
                );
            }
        }

        println!("===================================");
    }
}

// ============================================================================
// world_sync.rs
// ============================================================================

use crate::command::CommandBuffer;
use crate::entity::EntityId;

/// Synchronization point between stages
pub struct SyncPoint {
    pub command_buffers: Vec<CommandBuffer>,
    pub despawn_queue: Vec<EntityId>,
}

impl SyncPoint {
    /// Create new sync point
    pub fn new() -> Self {
        Self {
            command_buffers: Vec::new(),
            despawn_queue: Vec::new(),
        }
    }

    /// Add command buffer to flush
    pub fn add_command_buffer(&mut self, buffer: CommandBuffer) {
        self.command_buffers.push(buffer);
    }

    /// Queue entity for despawn
    pub fn queue_despawn(&mut self, entity: EntityId) {
        self.despawn_queue.push(entity);
    }

    /// Flush all commands to world
    pub fn flush(&mut self, world: &mut World) -> Result<()> {
        // Despawn entities (LIFO to maintain indices)
        for &entity in self.despawn_queue.iter().rev() {
            world.despawn(entity).ok();
        }
        self.despawn_queue.clear();

        // Flush command buffers
        for buffer in self.command_buffers.drain(..) {
            world.flush_commands(buffer)?;
        }

        Ok(())
    }
}

impl Default for SyncPoint {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// scheduler_debug.rs
// ============================================================================

use std::fs::File;
use std::io::Write;

/// Debug information about scheduling
#[derive(Debug, Clone)]
pub struct ScheduleDebugInfo {
    pub stage_count: usize,
    pub total_systems: usize,
    pub systems_per_stage: Vec<usize>,
}

impl ScheduleDebugInfo {
    /// Create from schedule
    pub fn from_schedule(schedule: &Schedule) -> Self {
        let stage_count = schedule.stage_count();
        let total_systems = schedule.system_count();
        let systems_per_stage = (0..stage_count)
            .map(|i| schedule.stage_system_count(i))
            .collect();

        Self {
            stage_count,
            total_systems,
            systems_per_stage,
        }
    }

    /// Print debug info
    pub fn print_debug(&self) {
        println!("Schedule Debug Info:");
        println!("  Total systems: {}", self.total_systems);
        println!("  Stages: {}", self.stage_count);
        for (i, &count) in self.systems_per_stage.iter().enumerate() {
            println!("    Stage {i}: {count} systems");
        }
    }

    /// Export as JSON (simplified)
    pub fn export_json(&self, filename: &str) -> std::io::Result<()> {
        let mut file = File::create(filename)?;
        write!(file, "{{")?;
        write!(file, "\"stage_count\":{},", self.stage_count)?;
        write!(file, "\"total_systems\":{},", self.total_systems)?;
        write!(file, "\"systems_per_stage\":[")?;
        for (i, &count) in self.systems_per_stage.iter().enumerate() {
            if i > 0 {
                write!(file, ",")?;
            }
            write!(file, "{count}")?;
        }
        write!(file, "]")?;
        write!(file, "}}")?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sync_point_creation() {
        let sp = SyncPoint::new();
        assert!(sp.command_buffers.is_empty());
        assert!(sp.despawn_queue.is_empty());
    }

    #[test]
    fn test_profiler_creation() {
        let profiler = SystemProfiler::new();
        assert!(profiler.timings.is_empty());
    }
}