Skip to content

Energy Perception & Physics Stability#139

Merged
M1thieu merged 6 commits intoerematorg:mainfrom
M1thieu:dev
Dec 31, 2025
Merged

Energy Perception & Physics Stability#139
M1thieu merged 6 commits intoerematorg:mainfrom
M1thieu:dev

Conversation

@M1thieu
Copy link
Collaborator

@M1thieu M1thieu commented Dec 31, 2025

Objective

Add energy-aware AI perception and fix critical physics stability issues.

Been waiting for MPM to finish but wanted to get actual game features in. This adds temperature/electric field sensing for creatures plus some needed physics infrastructure that was blocking progress.

Implementation

1. AI Energy Perception (New)

  • ThermalSensor/ThermalTracker: creatures sense temperature gradients
    • Detects hot/cold zones, calculates thermal comfort
    • Integrates with homeostasis needs (discomfort → need satisfaction)
    • Range-based sensing with sensitivity thresholds
  • ElectricSensor/ElectricTracker: electroreception (like sharks)
    • Superposition of electric fields (proper EM physics)
    • Creatures can detect and avoid electric hazards

Design: MPM-safe from the start. Trackers READ Temperature/ElectricField components that MPM will UPDATE later. No hardcoded physics, just perception layer.

2. Thermal Diffusion Stability (Critical Fix)

  • Added CFL condition check: dt ≤ C·dx²/α
  • Warns at startup if timestep will cause numerical explosion
  • Prevents "simulation goes to infinity" bugs before they happen

3. Wave Energy Conservation

  • Wave damping now reports energy loss to accounting ledger
  • Energy ∝ amplitude² (proper wave physics)
  • Records transactions for later MPM thermal coupling
  • Closes energy conservation gap

4. Forces Improvements (Pre-existing work merged)

  • Fixed mutual gravitational attraction (mutable aliasing bug)
  • Added symplectic Euler integration option
  • Forces diagnostics plugin (momentum/KE tracking for debugging)
  • Configurable integrator and gravity modes

Visibility cleanup:

  • Made internal system functions pub(crate) (better SoC)
  • Removed internal systems from public preludes

Testing

cargo check --all-targets  # Clean compile
cargo clippy --workspace   # No new warnings

Physics verified:

  • CFL condition: Industry-standard for explicit diffusion (same as CFD/climate models)
  • Wave energy: E ∝ A² is fundamental (sound, EM, water waves all follow this)
  • Electric superposition: Maxwell's equations (fields add vectorially)
  • Gravity: Newton's 3rd law (equal & opposite forces)
  • Symplectic Euler: Standard game physics integrator

Behavior:

  • Creatures with ThermalSensor actively seek comfortable temperatures
  • ElectricSensor lets them avoid electric hazards
  • Thermal comfort affects homeostasis need (0 discomfort = full satisfaction)

No breaking changes to existing APIs.

Code Example

Adding thermal sensing to a creature:

commands.spawn((
    Transform::default(),
    // Thermal perception
    ThermalSensor {
        range: 500.0,          // Sense up to 500 units away
        sensitivity: 5.0,       // Detect 5K temperature changes
        preferred_temp: 293.0,  // Likes room temperature (20°C)
    },
    ThermalTracker::default(),  // Auto-updated each frame
));

Reading thermal state:

fn creature_ai(creatures: Query<&ThermalTracker>) {
    for tracker in creatures.iter() {
        if tracker.discomfort > 0.5 {
            // Creature is uncomfortable!
            let direction = tracker.gradient_direction; // Points toward comfort
            // Move creature toward comfort...
        }
    }
}

Technical Notes

MPM Integration Path:

  • When MPM lands, it will own Temperature/ElectricField updates
  • AI trackers already designed to just READ those components
  • Zero refactoring needed when MPM arrives

Energy Conservation:

  • Wave damping → ledger
  • Thermal transfer → ledger (already done)
  • EM energy → ledger (future work)
  • MPM will close the loop by converting dissipated energy to heat

Limitations:

  • Thermal perception is simplified biophysics (good enough for gameplay)
  • Electric field sensing doesn't model conductivity yet (future)
  • CFL check is advisory (warns but doesn't auto-fix timestep)

Future trackers planned:

  • Acoustic sensing (sound waves)
  • Chemical sensing (smell/pheromones)
  • Pressure sensing (water flow, wind)

Replace 343 lines of manual distance calculations with EntityTracker + PreyTracker components, demonstrating the refactored AI architecture.

Changes:
- Use EntityTracker to store tracked food entities
- Use PreyTracker with evaluate_tracked_entities_with_decay() helper
- Remove custom Perception component (use tracker system instead)
- Remove altruistic behavior (too complex for basic example)
- Remove concurrent actions toggle (unnecessary)
- Simplify to 3 clear systems: track -> evaluate  -> move

Now properly showcases the tracker refactoring work and serves as a reference for using the AI system.
- Hash-based sparse spatial grid for infinite 2D worlds
- O(N²) → O(N) optimization for neighbor queries
- Cell-based partitioning with configurable cell size
- get_neighbors(), get_entities_in_radius() APIs
- Integrated into waves module for propagation
- Comprehensive test coverage
- Fix logo.png asset
Thermodynamics fixes and heat capacity implementation:
- First Law: ΔT = Q/C with real heat capacity
- Zeroth Law: Pure temperature equality for equilibrium
- Third Law: TODO comment for absolute zero behavior (awaiting MPM)
- HeatCapacity component with material helpers (water, air, iron, aluminum)
- Fallback to C = 1 J/K for abstract objects

Spatial grid optimization:
- Incremental GridCell updates with Changed<Transform> (O(N²) -> O(N))
- Auto-attach GridCell component to new entities
- move_entity() API for efficient cell transitions
- Applied to both thermal and wave systems
Add `EntityPool` + centralize component registration for LP (Mind = ECS, Body = SoA)

- Hard pool: strip on `release`, remove `Pooled` on `acquire`
- Central `UtilsPlugin` for `GridCell` & `Pooled` registration
- 13 tests passing, no deps added
- Clarified non-implemented physics: wave/EM energy ledger missing; EOS/phase/convection deferred; material responses (friction/contact/elastic/plastic) belong in matter/MPM; charge/mass/ang. momentum not conserved yet.
- Added NaN/Inf guards and TODOs for work->energy ledger and thermal energy bookkeeping.
- Added basic conservation/physics tests (momentum/KE, gravity symmetry/BH, ledger flux, thermal conduction/radiation) plus optional EnergyDriftMonitor diagnostic; minor cleanup in basic_save example.
Energy Module:
- Add CFL stability check for thermal diffusion (dt <= C*dx²/α)
- Implement wave damping energy accounting with ledger integration
- Track energy loss from wave damping (E ∝ amplitude²)

AI Systems:
- Add ThermalSensor/ThermalTracker for temperature perception
- Add ElectricSensor/ElectricTracker for electric field sensing
- Integrate thermal comfort with homeostasis needs
- MPM-safe design: trackers read components without owning solvers

Forces Module:
- Fix mutual gravitational attraction (resolve mutable aliasing)
- Add symplectic Euler integration option
- Add forces diagnostics plugin (momentum, kinetic energy tracking)
- Add configurable integrator and gravity force modes
@M1thieu M1thieu merged commit f6f98f1 into erematorg:main Dec 31, 2025
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant