Particle.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "definitions.hpp"
  2. #include "Particle.hpp"
  3. #include "Map.hpp"
  4. #include <cmath>
  5. Particle::Particle(fpoint_t position, fpoint_t direction):
  6. m_position(position), m_direction(direction)
  7. {
  8. }
  9. fpoint_t fit_map(fpoint_t point, numeric_t width, numeric_t height){
  10. if(point.x < 0){
  11. point.x += width;
  12. }
  13. if(point.y < 0){
  14. point.y += height;
  15. }
  16. if(point.x >= width){
  17. point.x -= width;
  18. }
  19. if(point.y >= height){
  20. point.y -= height;
  21. }
  22. return point;
  23. }
  24. fpoint_t ahead(fpoint_t point, fpoint_t direction, numeric_t distance){
  25. point.x += direction.x * distance;
  26. point.y += direction.y * distance;
  27. return point;
  28. }
  29. fpoint_t rotate(fpoint_t vec, numeric_t angle_deg){
  30. numeric_t C = cos(angle_deg * M_PI / 180.0);
  31. numeric_t S = sin(angle_deg * M_PI / 180.0);
  32. return {C * vec.x - S * vec.y, S * vec.x + C * vec.y};
  33. }
  34. size_t map_coord(fpoint_t point, icoord_t width, icoord_t height){
  35. return (size_t) floor(point.y) * (size_t) width + (size_t) floor(point.x);
  36. }
  37. size_t Particle::tile_index(Map const &map)
  38. {
  39. return map_coord(m_position, map.width(), map.height());
  40. }
  41. void Particle::update(Map const &map,
  42. numeric_t delta_t,
  43. numeric_t speed,
  44. numeric_t steering,
  45. numeric_t sampling_angle,
  46. numeric_t sampling_distance)
  47. {
  48. m_position.x += m_direction.x * speed * delta_t;
  49. m_position.y += m_direction.y * speed * delta_t;
  50. m_position = fit_map(m_position, map.width(), map.height());
  51. fpoint_t bit_ahead = fit_map(ahead(m_position, m_direction, sampling_distance), map.width(), map.height());
  52. fpoint_t bit_right = fit_map(ahead(m_position, rotate(m_direction, -sampling_angle), sampling_distance), map.width(), map.height());
  53. fpoint_t bit_left = fit_map(ahead(m_position, rotate(m_direction, sampling_angle), sampling_distance), map.width(), map.height());
  54. numeric_t pheromone_ahead = map.tiles()[map_coord(bit_ahead, map.width(), map.height())].pheromone;
  55. numeric_t pheromone_right = map.tiles()[map_coord(bit_right, map.width(), map.height())].pheromone;
  56. numeric_t pheromone_left = map.tiles()[map_coord(bit_left , map.width(), map.height())].pheromone;
  57. if (pheromone_right > pheromone_ahead && pheromone_right > pheromone_left)
  58. m_direction = rotate(m_direction, -steering * delta_t);
  59. else if(pheromone_left > pheromone_ahead && pheromone_left > pheromone_right)
  60. m_direction = rotate(m_direction, steering * delta_t);
  61. }