Removed unnecessary Player field
[entelect-challenge-tower-defence.git] / src / engine / bitwise_engine.rs
1 use engine::command::{Command, BuildingType};
2 use engine::geometry::Point;
3 use engine::constants::*;
4 use engine::status::GameStatus;
5
6 const LEFT_COL_MASK: u64 = 0x0101010101010101;
7 const RIGHT_COL_MASK: u64 = 0x8080808080808080;
8
9 #[derive(Debug, Clone, PartialEq, Eq)]
10 pub struct Player {
11     pub energy: u16,
12     pub health: u8
13 }
14
15 #[derive(Debug, Clone, PartialEq, Eq)]
16 pub struct BitwiseGameState {
17     pub status: GameStatus,
18     pub player: Player,
19     pub opponent: Player,
20     pub player_buildings: PlayerBuildings,
21     pub opponent_buildings: PlayerBuildings,
22 }
23
24 //TODO: Add in smallvec?
25 #[derive(Debug, Clone, PartialEq, Eq)]
26 pub struct PlayerBuildings {
27     pub unconstructed: Vec<UnconstructedBuilding>,
28     pub buildings: [u64; DEFENCE_HEALTH],
29     pub occupied: u64,
30     
31     pub energy_towers: u64,
32
33     pub missile_towers: [u64; MISSILE_COOLDOWN_STATES],
34     pub firing_tower: usize,
35     
36     pub missiles: [(u64, u64); MISSILE_MAX_SINGLE_CELL],
37     pub tesla_cooldowns: [TeslaCooldown; TESLA_MAX]
38 }
39
40 #[derive(Debug, Clone, PartialEq, Eq)]
41 pub struct UnconstructedBuilding {
42     pub pos: Point,
43     pub construction_time_left: u8,
44     pub building_type: BuildingType
45 }
46
47 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
48 pub struct TeslaCooldown {
49     pub active: bool,
50     pub pos: Point,
51     pub cooldown: u8,
52     pub age: u16
53 }
54
55
56 impl BitwiseGameState {
57     pub fn simulate(&mut self, player_command: Command, opponent_command: Command) -> GameStatus {
58         BitwiseGameState::perform_command(&mut self.player, &mut self.player_buildings, player_command);
59         BitwiseGameState::perform_command(&mut self.opponent, &mut self.opponent_buildings, opponent_command);
60
61         BitwiseGameState::update_construction(&mut self.player_buildings);
62         BitwiseGameState::update_construction(&mut self.opponent_buildings);
63         
64         BitwiseGameState::fire_teslas(&mut self.player, &mut self.player_buildings, &mut self.opponent, &mut self.opponent_buildings);
65
66         BitwiseGameState::add_missiles(&mut self.player_buildings);
67         BitwiseGameState::add_missiles(&mut self.opponent_buildings);
68
69         BitwiseGameState::move_and_collide_missiles(&mut self.player, &mut self.player_buildings, &mut self.opponent_buildings.missiles);
70         BitwiseGameState::move_and_collide_missiles(&mut self.opponent, &mut self.opponent_buildings, &mut self.player_buildings.missiles);
71
72         BitwiseGameState::add_energy(&mut self.player, &mut self.player_buildings);
73         BitwiseGameState::add_energy(&mut self.opponent, &mut self.opponent_buildings);
74
75         self.update_status();
76         self.status
77     }
78
79     pub fn player(&self) -> &Player { &self.player }
80     pub fn opponent(&self) -> &Player { &self.opponent }
81     pub fn player_has_max_teslas(&self) -> bool { self.player_buildings.count_teslas() >= TESLA_MAX }
82     pub fn opponent_has_max_teslas(&self) -> bool { self.opponent_buildings.count_teslas() >= TESLA_MAX }
83
84     pub fn unoccupied_player_cell_count(&self) -> usize { self.player_buildings.occupied.count_zeros() as usize }
85     pub fn unoccupied_opponent_cell_count(&self) -> usize { self.opponent_buildings.occupied.count_zeros() as usize }
86     pub fn location_of_unoccupied_player_cell(&self, i: usize) -> Point  {
87         let bit = find_bit_index_from_rank(self.player_buildings.occupied, i as u64);
88         let point = Point::new(bit%SINGLE_MAP_WIDTH, bit/SINGLE_MAP_WIDTH);
89         debug_assert!(point.to_either_bitfield() & self.player_buildings.occupied == 0);
90         point
91     }
92     pub fn location_of_unoccupied_opponent_cell(&self, i: usize) -> Point {
93         let bit = find_bit_index_from_rank(self.opponent_buildings.occupied, i as u64);
94         let point = Point::new(FULL_MAP_WIDTH - bit%SINGLE_MAP_WIDTH - 1, bit/SINGLE_MAP_WIDTH);
95         debug_assert!(point.to_either_bitfield() & self.opponent_buildings.occupied == 0);
96         point
97     }
98 }
99
100 fn find_bit_index_from_rank(occupied: u64, i: u64) -> u8 {
101     // Adapted from https://graphics.stanford.edu/~seander/bithacks.html#SelectPosFromMSBRank
102     let v = !occupied;
103     
104     let mut r = v.count_ones() as u64 - i as u64;
105
106     let a: u64 =  v - ((v >> 1) & !0u64/3);
107     let b: u64 = (a & (!0u64/5)) + ((a >> 2) & (!0u64/5));
108     let c: u64 = (b + (b >> 4)) & (!0u64/0x11);
109     let d: u64 = (c + (c >> 8)) & (!0u64/0x101);
110     let mut t: u64 = (d >> 32) + (d >> 48);
111
112     let mut s: u64 = 64;
113     s -= (t.wrapping_sub(r) & 256) >> 3; r -= t & (t.wrapping_sub(r) >> 8);
114     t  = (d >> (s - 16)) & 0xff;
115     s -= (t.wrapping_sub(r) & 256) >> 4; r -= t & (t.wrapping_sub(r) >> 8);
116     t  = (c >> (s - 8)) & 0xf;
117     s -= (t.wrapping_sub(r) & 256) >> 5; r -= t & (t.wrapping_sub(r) >> 8);
118     t  = (b >> (s - 4)) & 0x7;
119     s -= (t.wrapping_sub(r) & 256) >> 6; r -= t & (t.wrapping_sub(r) >> 8);
120     t  = (a >> (s - 2)) & 0x3;
121     s -= (t.wrapping_sub(r) & 256) >> 7; r -= t & (t.wrapping_sub(r) >> 8);
122     t  = (v >> (s - 1)) & 0x1;
123     s -= (t.wrapping_sub(r) & 256) >> 8;
124     s = 65 - s;
125
126     let bit = 64 - s as u8;
127     bit
128 }
129
130 impl BitwiseGameState {
131     pub fn new(
132         player: Player, opponent: Player,
133         player_buildings: PlayerBuildings, opponent_buildings: PlayerBuildings
134     ) -> BitwiseGameState {
135         BitwiseGameState {
136             status: GameStatus::Continue,
137             player, opponent,
138             player_buildings, opponent_buildings
139         }
140     }
141
142     /**
143      * Like with the expressive, this is to make things more
144      * comparable when writing tests, not for actual use in the
145      * engine.
146      */
147     #[cfg(debug_assertions)]
148     pub fn sort(&mut self) {
149         for i in 0..MISSILE_MAX_SINGLE_CELL {
150             for j in i+1..MISSILE_MAX_SINGLE_CELL {
151                 let move_down1 = !self.player_buildings.missiles[i].0 & self.player_buildings.missiles[j].0;
152                 self.player_buildings.missiles[i].0 |= move_down1;
153                 self.player_buildings.missiles[j].0 &= !move_down1;
154
155                 let move_down2 = !self.player_buildings.missiles[i].1 & self.player_buildings.missiles[j].1;
156                 self.player_buildings.missiles[i].1 |= move_down2;
157                 self.player_buildings.missiles[j].1 &= !move_down2;
158
159                 let move_down3 = !self.opponent_buildings.missiles[i].0 & self.opponent_buildings.missiles[j].0;
160                 self.opponent_buildings.missiles[i].0 |= move_down3;
161                 self.opponent_buildings.missiles[j].0 &= !move_down3;
162
163                 let move_down4 = !self.opponent_buildings.missiles[i].1 & self.opponent_buildings.missiles[j].1;
164                 self.opponent_buildings.missiles[i].1 |= move_down4;
165                 self.opponent_buildings.missiles[j].1 &= !move_down4;
166             }
167         }
168
169         self.player_buildings.unconstructed.sort_by_key(|b| b.pos);
170         self.opponent_buildings.unconstructed.sort_by_key(|b| b.pos);
171
172         for tesla in self.player_buildings.tesla_cooldowns.iter_mut() {
173             if !tesla.active {
174                 tesla.pos = Point::new(0,0);
175                 tesla.cooldown = 0;
176                 tesla.age = 0;
177             }
178         }
179         for tesla in self.opponent_buildings.tesla_cooldowns.iter_mut() {
180             if !tesla.active {
181                 tesla.pos = Point::new(0,0);
182                 tesla.cooldown = 0;
183                 tesla.age = 0;
184             }
185         }
186
187         self.player_buildings.tesla_cooldowns.sort_by_key(|b| (!b.active, b.pos));
188         self.opponent_buildings.tesla_cooldowns.sort_by_key(|b| (!b.active, b.pos));
189
190
191         while self.player_buildings.firing_tower > 0 {
192             self.player_buildings.firing_tower -= 1;
193             let zero = self.player_buildings.missile_towers[0];
194             for i in 1..self.player_buildings.missile_towers.len() {
195                 self.player_buildings.missile_towers[i-1] = self.player_buildings.missile_towers[i];
196             }
197             let end = self.player_buildings.missile_towers.len()-1;
198             self.player_buildings.missile_towers[end] = zero;
199         }
200         while self.opponent_buildings.firing_tower > 0 {
201             self.opponent_buildings.firing_tower -= 1;
202             let zero = self.opponent_buildings.missile_towers[0];
203             for i in 1..self.opponent_buildings.missile_towers.len() {
204                 self.opponent_buildings.missile_towers[i-1] = self.opponent_buildings.missile_towers[i];
205             }
206             let end = self.opponent_buildings.missile_towers.len()-1;
207             self.opponent_buildings.missile_towers[end] = zero;
208         }
209     }
210
211     #[cfg(debug_assertions)]
212     pub fn sorted(&self) -> BitwiseGameState {
213         let mut res = self.clone();
214         res.sort();
215         res
216     }
217
218     fn perform_command(player: &mut Player, player_buildings: &mut PlayerBuildings, command: Command) {
219         match command {
220             Command::Nothing => {},
221             Command::Build(p, b) => {
222                 let bitfield = p.to_either_bitfield();
223
224                 let price = match b {
225                     BuildingType::Attack => MISSILE_PRICE,
226                     BuildingType::Defence => DEFENCE_PRICE,
227                     BuildingType::Energy => ENERGY_PRICE,
228                     BuildingType::Tesla => TESLA_PRICE,
229                 };
230                 let construction_time = match b {
231                     BuildingType::Attack => MISSILE_CONSTRUCTION_TIME,
232                     BuildingType::Defence => DEFENCE_CONSTRUCTION_TIME,
233                     BuildingType::Energy => ENERGY_CONSTRUCTION_TIME,
234                     BuildingType::Tesla => TESLA_CONSTRUCTION_TIME,
235                 };
236
237                 // This is used internally. I should not be making
238                 // invalid moves!
239                 debug_assert!(player_buildings.buildings[0] & bitfield == 0);
240                 debug_assert!(p.x < FULL_MAP_WIDTH && p.y < MAP_HEIGHT);
241                 debug_assert!(player.energy >= price);
242                 debug_assert!(b != BuildingType::Tesla ||
243                               player_buildings.count_teslas() < TESLA_MAX);
244
245                 player.energy -= price;
246                 player_buildings.unconstructed.push(UnconstructedBuilding {
247                     pos: p,
248                     construction_time_left: construction_time,
249                     building_type: b
250                 });
251                 player_buildings.occupied |= bitfield;
252             },
253             Command::Deconstruct(p) => {
254                 let unconstructed_to_remove_index = player_buildings.unconstructed.iter().position(|ref b| b.pos == p);
255                 let deconstruct_mask = !(p.to_either_bitfield() & player_buildings.buildings[0]);
256                 
257                 debug_assert!(deconstruct_mask != 0 || unconstructed_to_remove_index.is_some());
258                 
259                 if let Some(i) = unconstructed_to_remove_index {
260                     player_buildings.unconstructed.swap_remove(i);
261                 }
262                 
263                 player.energy += DECONSTRUCT_ENERGY;
264                 
265                 for tier in 0..player_buildings.buildings.len() {
266                     player_buildings.buildings[tier] &= deconstruct_mask;
267                 }
268                 player_buildings.energy_towers &= deconstruct_mask;
269                 for tier in 0..player_buildings.missile_towers.len() {
270                     player_buildings.missile_towers[tier] &= deconstruct_mask;
271                 }
272                 for tesla in 0..player_buildings.tesla_cooldowns.len() {
273                     if player_buildings.tesla_cooldowns[tesla].pos == p {
274                         player_buildings.tesla_cooldowns[tesla].active = false;
275                     }
276                 }
277                 player_buildings.occupied &= deconstruct_mask;
278             }
279         }
280     }
281
282     fn update_construction(player_buildings: &mut PlayerBuildings) {
283         let mut buildings_len = player_buildings.unconstructed.len();
284         for i in (0..buildings_len).rev() {
285             if player_buildings.unconstructed[i].construction_time_left == 0 {
286                 let building_type = player_buildings.unconstructed[i].building_type;
287                 let health = if building_type == BuildingType::Defence { DEFENCE_HEALTH } else { 1 };
288                 
289                 let pos = player_buildings.unconstructed[i].pos;
290                 let bitfield = pos.to_either_bitfield();
291                 
292                 for health_tier in 0..health {
293                     player_buildings.buildings[health_tier] |= bitfield;
294                 }
295                 if building_type == BuildingType::Energy {
296                     player_buildings.energy_towers |= bitfield;
297                 }
298                 if building_type == BuildingType::Attack {
299                     player_buildings.missile_towers[player_buildings.firing_tower] |= bitfield;
300                 }
301                 if building_type == BuildingType::Tesla {
302                     let ref mut tesla_cooldown = if player_buildings.tesla_cooldowns[0].active {
303                         &mut player_buildings.tesla_cooldowns[1]
304                     } else {
305                         &mut player_buildings.tesla_cooldowns[0]
306                     };
307                     tesla_cooldown.active = true;
308                     tesla_cooldown.pos = pos;
309                     tesla_cooldown.cooldown = 0;
310                     tesla_cooldown.age = 0;
311                 }
312                 
313                 buildings_len -= 1;
314                 player_buildings.unconstructed.swap(i, buildings_len);
315             } else {
316                 player_buildings.unconstructed[i].construction_time_left -= 1
317             }
318         }
319         player_buildings.unconstructed.truncate(buildings_len);
320     }
321
322     fn fire_teslas(player: &mut Player, player_buildings: &mut PlayerBuildings, opponent: &mut Player, opponent_buildings: &mut PlayerBuildings) {
323         BitwiseGameState::fire_single_players_teslas_without_cleanup(player, player_buildings, opponent, opponent_buildings);
324         BitwiseGameState::fire_single_players_teslas_without_cleanup(opponent, opponent_buildings, player, player_buildings);
325
326         BitwiseGameState::update_tesla_activity(player_buildings);
327         BitwiseGameState::update_tesla_activity(opponent_buildings);
328     }
329
330     fn fire_single_players_teslas_without_cleanup(player: &mut Player, player_buildings: &mut PlayerBuildings, opponent: &mut Player, opponent_buildings: &mut PlayerBuildings) {
331         player_buildings.tesla_cooldowns.sort_unstable_by(|a, b| b.age.cmp(&a.age));
332         for tesla in player_buildings.tesla_cooldowns.iter_mut().filter(|t| t.active) {
333             tesla.age += 1;
334             if tesla.cooldown > 0 {
335                 tesla.cooldown -= 1;
336             } else if player.energy >= TESLA_FIRING_ENERGY {
337                 player.energy -= TESLA_FIRING_ENERGY;
338                 tesla.cooldown = TESLA_COOLDOWN;
339
340                 let flipped_pos = tesla.pos.flip_x();
341
342                 if flipped_pos.x >= SINGLE_MAP_WIDTH - 1 {
343                     opponent.health = opponent.health.saturating_sub(TESLA_DAMAGE);
344                 }
345
346                 let missed_cells = ((SINGLE_MAP_WIDTH - flipped_pos.x) as u32).saturating_sub(2);
347                 
348                 let top_row = if tesla.pos.y == 0 { 0 } else { tesla.pos.y - 1 };
349                 let top_row_mask = 255u64 << (top_row * SINGLE_MAP_WIDTH);
350                 let mut destroy_mask = top_row_mask.wrapping_shl(missed_cells) & top_row_mask;
351
352                 let mut hits = 0;
353                 for _ in 0..(if tesla.pos.y == 0 || tesla.pos.y == MAP_HEIGHT-1 { 2 } else { 3 }) {
354                     hits |= destroy_mask & opponent_buildings.buildings[0];
355                     destroy_mask &= !hits;
356                     destroy_mask = destroy_mask << SINGLE_MAP_WIDTH;
357                 }
358                 BitwiseGameState::destroy_buildings(opponent_buildings, hits);
359             }
360         }
361     }
362
363     fn add_missiles(player_buildings: &mut PlayerBuildings) {
364         let mut missiles = player_buildings.missile_towers[player_buildings.firing_tower];
365         for mut tier in player_buildings.missiles.iter_mut() {
366             let setting = !tier.0 & missiles;
367             tier.0 |= setting;
368             missiles &= !setting;
369         }
370         player_buildings.firing_tower = (player_buildings.firing_tower + 1) % MISSILE_COOLDOWN_STATES;
371     }
372
373     fn move_and_collide_missiles(opponent: &mut Player, opponent_buildings: &mut PlayerBuildings, player_missiles: &mut [(u64, u64); MISSILE_MAX_SINGLE_CELL]) {
374         let mut destroyed = 0;
375         let mut damaging = 0;
376         for _ in 0..MISSILE_SPEED {
377             for i in 0..MISSILE_MAX_SINGLE_CELL {
378                 let swapping_sides = player_missiles[i].0 & RIGHT_COL_MASK;
379                 let about_to_hit_opponent = player_missiles[i].1 & LEFT_COL_MASK;
380
381                 player_missiles[i].0 = (player_missiles[i].0 & !RIGHT_COL_MASK) << 1;
382                 player_missiles[i].1 = ((player_missiles[i].1 & !LEFT_COL_MASK) >> 1) | swapping_sides;
383
384                 damaging = (damaging << 1) | about_to_hit_opponent;
385
386                 let mut hits = 0;
387                 for health_tier in (0..DEFENCE_HEALTH).rev() {
388                     hits = opponent_buildings.buildings[health_tier] & player_missiles[i].1;
389                     player_missiles[i].1 &= !hits;
390                     opponent_buildings.buildings[health_tier] &= !hits;
391                 }
392                 destroyed |= hits;
393             }
394         }
395         let damage = damaging.count_ones() as u8 * MISSILE_DAMAGE;
396         opponent.health = opponent.health.saturating_sub(damage);
397
398         BitwiseGameState::destroy_buildings(opponent_buildings, destroyed);
399         BitwiseGameState::update_tesla_activity(opponent_buildings);
400     }
401
402     fn destroy_buildings(buildings: &mut PlayerBuildings, hit_mask: u64) {
403         let deconstruct_mask = !hit_mask;
404         
405         buildings.energy_towers &= deconstruct_mask;
406         for tier in buildings.missile_towers.iter_mut() {
407             *tier &= deconstruct_mask;
408         }
409         for tier in buildings.buildings.iter_mut() {
410             *tier &= deconstruct_mask;
411         }
412         buildings.occupied &= deconstruct_mask;
413     }
414
415     fn update_tesla_activity(buildings: &mut PlayerBuildings) {
416         for i in 0..TESLA_MAX {
417             buildings.tesla_cooldowns[i].active = buildings.tesla_cooldowns[i].active && (buildings.tesla_cooldowns[i].pos.to_either_bitfield() & buildings.occupied) != 0;
418         }
419     }
420     
421     
422     fn add_energy(player: &mut Player, player_buildings: &mut PlayerBuildings) {
423         player.energy += player_buildings.energy_generated();
424     }
425
426     fn update_status(&mut self) {
427         let player_dead = self.player.health == 0;
428         let opponent_dead = self.opponent.health == 0;
429         self.status = match (player_dead, opponent_dead) {
430             (true, true) => GameStatus::Draw,
431             (false, true) => GameStatus::PlayerWon,
432             (true, false) => GameStatus::OpponentWon,
433             (false, false) => GameStatus::Continue,
434         };
435     }
436
437 }
438
439 impl PlayerBuildings {
440     pub fn count_teslas(&self) -> usize {
441         self.tesla_cooldowns.iter().filter(|t| t.active).count()
442             + self.unconstructed.iter().filter(|t| t.building_type == BuildingType::Tesla).count()
443     }
444
445     pub fn empty() -> PlayerBuildings {
446         PlayerBuildings {
447             unconstructed: Vec::with_capacity(4),
448             buildings: [0; DEFENCE_HEALTH],
449             occupied: 0,
450             energy_towers: 0,
451             missile_towers: [0; MISSILE_COOLDOWN_STATES],
452             firing_tower: 0,
453             missiles: [(0,0); MISSILE_MAX_SINGLE_CELL],
454             tesla_cooldowns: [TeslaCooldown::empty(); TESLA_MAX]
455         }
456     }
457
458     pub fn energy_generated(&self) -> u16 {
459         ENERGY_GENERATED_BASE + self.energy_towers.count_ones() as u16 * ENERGY_GENERATED_TOWER
460     }
461 }
462
463 impl TeslaCooldown {
464     pub fn empty() -> TeslaCooldown {
465         TeslaCooldown {
466             active: false,
467             pos: Point::new(0,0),
468             cooldown: 0,
469             age: 0
470         }
471     }
472 }