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