summaryrefslogtreecommitdiff
path: root/src/sim/entity/mod.rs
blob: 61f9d84a8159191695425ad7580d645101ea4dd5 (plain)
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
use glam::{IVec2, Vec2};
use rapier2d::{
    dynamics::{RigidBody, RigidBodyBuilder, RigidBodyHandle},
    geometry::{Collider, ColliderHandle},
};

use crate::{
    config::MASS_SCALING,
    content::materials::MaterialId,
    sim::{
        cell::Cell, lib::marching_squares::Marchable, rb_manager::RbManager, sim_manager::SimCtx,
    },
    sprite_loader::load_sprite_to_cells,
};

pub struct EntityCells {
    pub size: IVec2,
    pub cells: Vec<Cell>,
}

impl EntityCells {
    #[inline]
    pub fn get_cell_at_local_position(&self, pos: IVec2) -> Cell {
        self.cells[pos.x as usize + pos.y as usize * self.size.x as usize]
    }
    #[inline]
    pub fn set_cell_at_local_position(&mut self, pos: IVec2, cell: Cell) {
        self.cells[pos.x as usize + pos.y as usize * self.size.x as usize] = cell;
    }

    pub fn mass(&self) -> f32 {
        self.cells
            .iter()
            .fold(0.0, |acc, cur| acc + cur.material.def().density as f32)
            * MASS_SCALING
    }

    pub fn flip_x(&mut self) {
        let mut new_cells = Vec::with_capacity(self.cells.len());
        for y in 0..self.size.y {
            for rx in 0..self.size.x {
                let x = self.size.x - rx - 1;
                new_cells.push(self.get_cell_at_local_position(IVec2::new(x, y)));
            }
        }

        self.cells = new_cells;
    }
}

impl Marchable for EntityCells {
    fn occupied(&self, pos: IVec2) -> bool {
        if pos.x < 0 || pos.x >= self.size.x || pos.y < 0 || pos.y >= self.size.y {
            false
        } else {
            self.get_cell_at_local_position(pos).material != MaterialId::Void
        }
    }
    fn marchable_size(&self) -> IVec2 {
        self.size
    }
}

pub trait EntityBehaviour {
    // TODO merge ctxs?
    fn update(&mut self, _update_ctx: &mut EntityUpdateCtx, _ctx: &mut SimCtx, _delta_time: f32) {}
    fn physics_update(
        &mut self,
        _update_ctx: &mut EntityUpdateCtx,
        _ctx: &mut SimCtx,
        _delta_time: f32,
    ) {
    }
}

pub struct EntityDef {
    pub rb: Option<RigidBody>,
    pub collider: Option<Collider>,
    pub cells: Option<EntityCells>,
    pub behaviour: Option<Box<dyn EntityBehaviour>>,
}

impl EntityDef {
    pub fn from_cells_and_rb(
        cells: EntityCells,
        rb: RigidBody,
        behaviour: Option<Box<dyn EntityBehaviour>>,
    ) -> Self {
        let collider = RbManager::convex_hull_collider_from_marchable(&cells, Some(10))
            .mass(cells.mass())
            .build();

        EntityDef {
            rb: Some(rb),
            collider: Some(collider),
            cells: Some(cells),
            behaviour,
        }
    }

    pub fn from_cells(
        position: Vec2,
        cells: EntityCells,
        behaviour: Option<Box<dyn EntityBehaviour>>,
    ) -> Self {
        let rb = RigidBodyBuilder::dynamic().translation(position).build();

        let collider = RbManager::convex_hull_collider_from_marchable(&cells, Some(10))
            .mass(cells.mass())
            .build();

        EntityDef {
            rb: Some(rb),
            collider: Some(collider),
            cells: Some(cells),
            behaviour,
        }
    }

    pub fn from_sprite(
        position: Vec2,
        path: &str,
        behaviour: Option<Box<dyn EntityBehaviour>>,
    ) -> Self {
        let sprite_cells = load_sprite_to_cells(path);
        let mut entity_cells = EntityCells {
            cells: sprite_cells.cells,
            size: IVec2::new(sprite_cells.width as i32, sprite_cells.height as i32),
        };

        entity_cells
            .cells
            .iter_mut()
            .for_each(|c| c.set_entity_integrated(true));

        EntityDef::from_cells(position, entity_cells, behaviour)
    }

    pub fn kinematic_from_cells(
        position: Vec2,
        cells: EntityCells,
        behaviour: Option<Box<dyn EntityBehaviour>>,
    ) -> Self {
        let rb = RigidBodyBuilder::kinematic_velocity_based()
            .translation(position)
            .build();

        let collider = RbManager::convex_hull_collider_from_marchable(&cells, Some(10))
            .mass(cells.mass())
            .build();

        EntityDef {
            rb: Some(rb),
            collider: Some(collider),
            cells: Some(cells),
            behaviour,
        }
    }

    pub fn kinematic_from_sprite(
        position: Vec2,
        path: &str,
        behaviour: Option<Box<dyn EntityBehaviour>>,
    ) -> Self {
        let sprite_cells = load_sprite_to_cells(path);
        let mut entity_cells = EntityCells {
            cells: sprite_cells.cells,
            size: IVec2::new(sprite_cells.width as i32, sprite_cells.height as i32),
        };

        entity_cells
            .cells
            .iter_mut()
            .for_each(|c| c.set_entity_integrated(true));

        EntityDef::kinematic_from_cells(position, entity_cells, behaviour)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub struct EntityId(pub u32);

pub struct EntityData {
    pub id: EntityId,
    pub rb_h: Option<RigidBodyHandle>,
    pub collider_h: Option<ColliderHandle>,
    pub cells: Option<EntityCells>,
}

pub struct EntityUpdateResult {
    pub deferred_destructions: Vec<EntityId>,
}

pub struct EntityUpdateCtx<'a> {
    pub entity_data: &'a mut EntityData,
    deferred_destructions: Vec<EntityId>,
}

impl<'a> EntityUpdateCtx<'a> {
    pub fn from_entity_data(entity_data: &'a mut EntityData) -> Self {
        EntityUpdateCtx {
            entity_data,
            deferred_destructions: Vec::new(),
        }
    }
    pub fn deferred_destroy(&mut self, entity_id: EntityId) {
        self.deferred_destructions.push(entity_id);
    }
    pub fn to_result(self) -> EntityUpdateResult {
        EntityUpdateResult {
            deferred_destructions: self.deferred_destructions,
        }
    }
}

impl EntityData {
    pub fn _linvel(&self, rb_manager: &RbManager) -> Option<Vec2> {
        self.rb_h.and_then(|rb_h| {
            rb_manager
                .physics_manager
                .world
                .bodies
                .get(rb_h)
                .map(|rb| rb.linvel())
        })
    }
    pub fn _transform(&self, rb_manager: &RbManager) -> Option<(Vec2, (f32, f32))> {
        self.rb_h.and_then(|rb_h| {
            rb_manager
                .physics_manager
                .world
                .bodies
                .get(rb_h)
                .map(|rb| (rb.translation(), (rb.rotation().cos(), rb.rotation().sin())))
        })
    }
    pub fn transform(&self, ctx: &SimCtx) -> Option<(Vec2, (f32, f32))> {
        self._transform(ctx.rb_manager)
    }
}

pub struct Entity {
    pub data: EntityData,
    behaviour: Option<Box<dyn EntityBehaviour>>,
}

impl Entity {
    pub fn update(&mut self, ctx: &mut SimCtx, delta_time: f32) -> Option<EntityUpdateResult> {
        if let Some(behaviour) = &mut self.behaviour {
            let mut ectx = EntityUpdateCtx::from_entity_data(&mut self.data);
            behaviour.update(&mut ectx, ctx, delta_time);
            return Some(ectx.to_result());
        }
        None
    }

    pub fn physics_update(
        &mut self,
        ctx: &mut SimCtx,
        delta_time: f32,
    ) -> Option<EntityUpdateResult> {
        if let Some(behaviour) = &mut self.behaviour {
            let mut ectx = EntityUpdateCtx::from_entity_data(&mut self.data);
            behaviour.physics_update(&mut ectx, ctx, delta_time);
            return Some(ectx.to_result());
        }
        None
    }

    pub fn compute_collider(&self) -> Option<Collider> {
        self.data.cells.as_ref().map(|cells| {
            RbManager::convex_hull_collider_from_marchable(cells, Some(10))
                .mass(cells.mass())
                .build()
        })
    }

    pub fn new(
        id: EntityId,
        rb_h: Option<RigidBodyHandle>,
        collider_h: Option<ColliderHandle>,
        cells: Option<EntityCells>,
        behaviour: Option<Box<dyn EntityBehaviour>>,
    ) -> Self {
        Entity {
            data: EntityData {
                id,
                rb_h,
                collider_h,
                cells,
            },
            behaviour,
        }
    }
}