]> git.tdb.fi Git - libs/game.git/blob - examples/bassteroids/source/physics.h
fcf4b0dce534396434b5d6667a654f9aeb73e502
[libs/game.git] / examples / bassteroids / source / physics.h
1 #ifndef PHYSICS_H_
2 #define PHYSICS_H_
3
4 #include <msp/game/eventobserver.h>
5 #include <msp/game/eventsource.h>
6 #include <msp/game/events.h>
7 #include <msp/game/handle.h>
8 #include <msp/game/system.h>
9 #include <msp/geometry/angle.h>
10 #include <msp/linal/vector.h>
11 #include "events.h"
12
13 class PhysicalEntity;
14
15 class Physics: public Msp::Game::System
16 {
17 public:
18         using EventSource = Msp::Game::EventSource<Events::Collision>;
19
20 private:
21         struct SimulatedEntity
22         {
23                 Msp::Game::Handle<PhysicalEntity> entity;
24                 float inverse_mass = 1.0f;
25                 float inverse_momi = 1.0f;
26                 Msp::LinAl::Vector<float, 2> external_force;
27                 float external_torque = 0.0f;
28
29                 Msp::LinAl::Vector<float, 2> position;
30                 Msp::Geometry::Angle<float> rotation;
31                 Msp::LinAl::Vector<float, 2> velocity;
32                 Msp::Geometry::Angle<float> angular_velocity;
33
34                 unsigned collision_count;
35                 Msp::LinAl::Vector<float, 2> position_adjust;
36         };
37
38         struct Collision
39         {
40                 std::uint16_t body1 = 0;
41                 std::uint16_t body2 = 0;
42                 Msp::LinAl::Vector<float, 2> point;
43                 float depth = 0.0f;
44                 Msp::LinAl::Vector<float, 2> normal;
45         };
46
47         EventSource event_source;
48         Msp::Game::EventObserver observer;
49         std::vector<SimulatedEntity> entities;
50         unsigned fixture_count = 0;
51         std::vector<Collision> collisions;
52
53 public:
54         Physics(Msp::Game::Stage &);
55
56 private:
57         void entity_added(const Msp::Game::Events::EntityCreated &);
58
59 public:
60         void tick(Msp::Time::TimeDelta) override;
61
62 private:
63         template<bool>
64         void copy_in(SimulatedEntity &);
65
66         template<bool>
67         void copy_out(SimulatedEntity &);
68
69         void step(float);
70         void detect_collisions();
71         void solve_collisions();
72         void apply_impulses();
73
74         Collision &get_collision(unsigned, unsigned);
75         void collide_circle_circle(unsigned, unsigned);
76         void collide_circle_box(unsigned, unsigned);
77 };
78
79 #endif